Search code examples
pythonregexpython-re

Search string that contains WORD with \W or ^ before and \W or $ after


How to simplify following regular expression

re.search(f'\W{word}\W', text) or re.search(f'^{word}\W', text) or re.search(f'\W{word}$', text) or word == text

i.e. return True for any string that contains word with \W or ^ before and \W or $ after.

Variants

  1. re.search(f'[^\W]{word}[\W$]', text)
  2. re.search(f'[\W^]{word}[\W$]', text)

dont work for my case.

Expression re.search(f'\W*{word}\W*', text) gives wrong matches, for example word + 'A'.

Any suggestions? Thank you!


Solution

  • There is no simple way to make ^ or $ optional patterns in Python's regexps.

    I think the easiest way will be to concatenate the three regexps, but using the | operator inside the expression instead of the external or with 3 .search calls:

    word = re.escape(ticker.lower())
    result = re.search(f"(^{word}\W)|(\W{word}\W)|(\W{word}$)"`