如果所有给定单词都在字符串中,则匹配正则表达式

时间:2022-09-13 12:15:54

Say I have a query like this: "one two three", if I replace with spaces with | (pipe character) I can match a string if it contains one or more of those words. This is like a logical OR.

假设我有这样的查询:“一二三”,如果我用|替换空格(管道符)如果字符串包含一个或多个单词,我可以匹配它。这就像逻辑OR。

Is there something similar that does a logical AND. It should match regardless of word ordering as long as all the words are present in the string.

是否存在类似的逻辑AND。只要字符串中存在所有单词,它就应该匹配,无论单词排序如何。

Unfortunately I'm away from my Mastering Regular Expressions book :(

不幸的是,我离开了我的Mastering Regular Expressions书:(

Edit: I'm using Javascript and the query can contain any amount of words.

编辑:我正在使用Javascript,查询可以包含任意数量的单词。

3 个解决方案

#1


6  

Try look-ahead assertions:

尝试前瞻断言:

(?=.*one)(?=.*two)(?=.*three)

But it would be better if you use three separate regular expressions or simpler string searching operations.

但是如果你使用三个单独的正则表达式或更简单的字符串搜索操作会更好。

#2


2  

There's nothing really good for that. You could fairly easily match on three occurrences of any of the words involved:

对此没有什么好处。您可以很容易地匹配任何相关单词的三次出现:

(?:\b(?:one|two|three)\b.*){3}

but that matches "one one one" as easily as "one two three".

但这与“一二三”一样容易“匹配”。

You can use lookahead assertions like Gumbo describes. Or you can write out the permutations, like so:

您可以使用像Gumbo描述的前瞻断言。或者你可以写出排列,如下:

(?\bone\b.*\btwo\b.*\bthree\b|\btwo\b.*\bone\b.*\bthree\b|\bone\b.*\bthree\b.*\btwo\b|\bthree\b.*\bone\b.*\btwo\b|\bthree\b.*\btwo\b.*\bone\b|\btwo\b.*\bthree\b.*\bone\b)

which is obviously horrible.

这显然是可怕的。

Long story short, it's a lot better to do three separate matches.

长话短说,做三场独立比赛要好得多。

#3


2  

Do three separate matches.

The only reason to do it in one, is if you needed it to find them in a specific order.

在一个中完成它的唯一原因是,如果您需要它以特定顺序找到它们。

#1


6  

Try look-ahead assertions:

尝试前瞻断言:

(?=.*one)(?=.*two)(?=.*three)

But it would be better if you use three separate regular expressions or simpler string searching operations.

但是如果你使用三个单独的正则表达式或更简单的字符串搜索操作会更好。

#2


2  

There's nothing really good for that. You could fairly easily match on three occurrences of any of the words involved:

对此没有什么好处。您可以很容易地匹配任何相关单词的三次出现:

(?:\b(?:one|two|three)\b.*){3}

but that matches "one one one" as easily as "one two three".

但这与“一二三”一样容易“匹配”。

You can use lookahead assertions like Gumbo describes. Or you can write out the permutations, like so:

您可以使用像Gumbo描述的前瞻断言。或者你可以写出排列,如下:

(?\bone\b.*\btwo\b.*\bthree\b|\btwo\b.*\bone\b.*\bthree\b|\bone\b.*\bthree\b.*\btwo\b|\bthree\b.*\bone\b.*\btwo\b|\bthree\b.*\btwo\b.*\bone\b|\btwo\b.*\bthree\b.*\bone\b)

which is obviously horrible.

这显然是可怕的。

Long story short, it's a lot better to do three separate matches.

长话短说,做三场独立比赛要好得多。

#3


2  

Do three separate matches.

The only reason to do it in one, is if you needed it to find them in a specific order.

在一个中完成它的唯一原因是,如果您需要它以特定顺序找到它们。