Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression matching [^a-z] or $

Tags:

python

regex

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?

like image 492
Chris Seymour Avatar asked Nov 22 '25 07:11

Chris Seymour


1 Answers

You can use a negative lookahead:

'test(?![a-z])'

Or an alternation:

'test([^a-z]|$)'
like image 123
Mark Byers Avatar answered Nov 24 '25 19:11

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!