Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - match string NOT containing one group, DOES contain another

Tags:

regex

perl

For example, a regular expression that matches a string that does not contain "foo" but does contain "bar". I do not have the luxury of using two expressions. I need to do it in one expression.

ex.:

"this is foo baz bar" - should not match
"this is foo baz" - should not match
"this is baz bar" - should match

I'm in Perl, fwiw

like image 479
beasy Avatar asked Dec 24 '22 21:12

beasy


1 Answers

Use a negative lookahead assertion at the start to check for the string not contain any foo substring.

^(?!.*?foo).*bar.*

OR

^(?!.*?\bfoo\b).*\bbar\b.*

DEMO

like image 150
Avinash Raj Avatar answered Dec 27 '22 11:12

Avinash Raj