开发者

Regular expression: which pattern would return true if both exact words were found?

开发者 https://www.devze.com 2023-03-27 09:32 出处:网络
If my regex pattern @\"\\b(word1|word2)\\b\" returns true when only 1 of the exact words is found, which pattern would return true if both exact words were found?

If my regex pattern @"\b(word1|word2)\b" returns true when only 1 of the exact words is found, which pattern would return true if both exact words were found?

The only examples I found were like I did it and return true whenever 1 word was found but I want it to return true when all words were found. So multiples of the same word don't count. I need to know if at least 1 occurrence of all words exists.

Edit:

Example: "The q开发者_StackOverflow社区uick brown fox jumps over the lazy dog"

pattern: @"\b(fox|dog)\b" <---- returns true

pattern: @"\b(fox|elephant)\b" <---- returns true, I want it to return false.

Add: I have to be flexible since the amount of words to search for depends on my users.


You can achieve this using lookaheads

(?=.*\bWord1\b)(?=.*\bWord2\b).*

See it here on Regexr

(?=.*\bWord1\b) is a positive lookahead. It checks if the pattern inside occurs within the string. It does not match anything!

To match the string there is the .* at the end, but this will only be matched, if both lookaheads are true, i.e. both of your words are found within the string.


the simple answer is to have two regex expressions one for the first word, and one for the other, if both return true (and them), then the result is true.

@"\b(word1)\b" and @"\b(word2)\b"

You can check here also


If you must,

@"\b(word1\b(.*\b)?word2|word2\b(.*\b)?word1)\b"

but it would be better to use two regular expressions.


Stema's answer is the best imo.

The following is a simplified version of Charles

Given: "word and word2 and word3 and word4. word4 is a good guy, isn't he word1?"

(\bword4\b.\bword2\b|\bword2\b.\bword4\b)

BUT like i said Stema ftw

0

精彩评论

暂无评论...
验证码 换一张
取 消