gmc
gmc

Reputation: 3990

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.

Upvotes: 4

Views: 5154

Answers (2)

JvdV
JvdV

Reputation: 75900

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.

Upvotes: 4

Alireza
Alireza

Reputation: 2123

Use this pattern:

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

See Demo

Upvotes: 3

Related Questions