Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match strings that do NOT contain all specified elements

I'd like to find a regular expression that matches strings that do NOT contain all the specified elements, independently of their order. For example, given the following data:

one two three four
one three two
one two
one three
four

Passing the words two three to the regex should match the lines one two, one three and four.

I know how to implement an expression that matches lines that do not contain ANY of the words, matching only line four:

^((?!two|three).)*$

But for the case I'm describing, I'm lost.

like image 474
gmc Avatar asked Oct 22 '25 09:10

gmc


2 Answers

Nice question. It looks like you are looking for some AND logic. I am sure someone can come up with something better, but I thought of two ways:

^(?=(?!.*\btwo\b)|(?!.*\bthree\b)).*$

See the online demo

Or:

^(?=.*\btwo\b)(?=.*\bthree\b)(*SKIP)(*F)|^.*$

See the online demo

In both cases we are using positive lookahead to mimic the AND logic to prevent both words being present in a text irrespective of their position in the full string. If just one of those words is present, the string will pass.

like image 167
JvdV Avatar answered Oct 24 '25 01:10

JvdV


Use this pattern:

(?!.*two.*three|.*three.*two)^.*$

See Demo

like image 36
Alireza Avatar answered Oct 24 '25 00:10

Alireza



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!