I need some help with string regex matching a word in a sentence accounting for punctuation and the end of the line. My attempt fails for the end of line case.
The following examples evaluate as I need:
>>> print bool(re.search('test[^a-z]','test!'.lower()))
True
>>> print bool(re.search('test[^a-z]','test aaa'.lower()))
True
>>> print bool(re.search('test[^a-z]','testaaa'.lower()))
False
However the end of line case evaluates False:
>>> print bool(re.search('test[^a-z]','test'.lower()))
False
The end of line character $ isn't in the set a-z so locigal I thought this case would also evaluate True. How can I handle this in regex?
You can use a negative lookahead:
'test(?![a-z])'
Or an alternation:
'test([^a-z]|$)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With