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
re.search(f'[^\W]{word}[\W$]', text)
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!
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}$)"`