简体   繁体   中英

Regex - excluding words but with wildcards

May not be possible with one expression but here goes.

txt = 'check from HERE and i need RED but not BLUE'

For the above text I need an expression that will match if 'RED' appears anywhere after 'HERE' but 'BLUE' does not appear anywhere after HERE.

For posterity:

Without regular expressions

txt = 'check from HERE and i need RED but not BLUE'
after_here = txt.split('HERE', 1)[1]
result = red in after_here and blue not in after_here

Regular expression

^.*HERE(?!.*BLUE.*).*RED.*$
#   ^ look after 'HERE'
#           ^ negative lookahead in everything that comes after HEAD for BLUE
#                     ^ look for RED in everything that comes after HEAD

// see https://www.regular-expressions.info/lookaround2.html

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