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.
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.
Use this pattern:
(?!.*two.*three|.*three.*two)^.*$
See Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With