Skip to main content
 首页 » 编程设计

c#之在 .net 中用正则表达式匹配两个单词的正确模式

2024年02月05日27zhwl

我想过滤包含两个特定单词的句子。我搜索了合适的模式,我得到了这个:

/^(?=.*\bWord1\b)(?=.*\bWord2\b).*$/ 

但它在 .Net Regex 中不起作用。 在 .net Regex 类中用正则表达式匹配两个单词的正确模式是什么?

提前致谢

请您参考如下方法:

正则表达式错误

^(?=.\bWord1\b)(?=.\bWord1\b) 

您的正则表达式表示匹配一个非单词(由于 ^ 在句子的开头)并找到 Word1。 Word2 也是如此。所以基本上你是说在看到一个字母后找到这两个词。

^(non-word) <spaces only for clarity> Word1 
  <------>                            <---> 
First . of            and   ==>       Find 
lookahead             then  ==>       Word1 
matches this 
<--------------> 
As lookaheads are of zero width, the same thing will be applied for Word2.  
So, we are finding Word1 and Word2 both at same position which can't be possible. 
Also your words can be anywhere in sentence and not just after first position. 

更正正则表达式

^(?=.*\bword1\b)(?=.*\bword2\b).*$ 

regexstorm demo

正则表达式分解

^ #Starting of string 
 (?=.*\bword1\b) #Lookahead to find word1 anywhere in the sentence 
 (?=.*\bword2\b) #Lookahead to find word2 anywhere in the sentence 
 .* #If both of above is true, then find the whole sentence 
$ #End of string 

C# 代码

string input = "word1 abcdkl word2"; 
Regex regex = new Regex(@"^(?=.*\bword1\b)(?=.*\bword2\b).*$"); 
 
Match match = regex.Match(input); 
 
if (match.Success) 
{ 
    Console.WriteLine(match.Groups[0].Value);    
} 

Ideone Demo