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

浪尽此生 提交于 2021-02-05 06:30:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!