问题
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.
回答1:
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.
回答2:
Use this pattern:
(?!.*two.*three|.*three.*two)^.*$
See Demo
来源:https://stackoverflow.com/questions/64782707/regular-expression-to-match-strings-that-do-not-contain-all-specified-elements