简体   繁体   中英

Regular expression matching [^a-z] or $

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 az 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]|$)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM