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

Question:

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!

Asked By: Che4ako

||

Answers:

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}$)"`
Answered By: jsbueno
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.