Skip to main content
 首页 » 编程设计

c#之我怎样才能阻止这个正则表达式变得贪婪呢

2024年01月22日25bhlsheji

当前,此正则表达式返回一个匹配项:


  最好的语言
  世界和最快的语言


如何获取返回两个匹配项的信息:


  最好的语言
  
  最快的语言


string text = "C# is the best language in the world and the fastest language in the world"; 
string search = @"\bthe\b.*\blanguage\b"; 
MatchCollection matches = Regex.Matches(text, search); 
Console.WriteLine("{0} matches", matches.Count); 
foreach (Match match in matches) 
{ 
    Console.WriteLine("match '{0}' was found at index {1}", match.Value, match.Index); 
} 
Console.WriteLine("---"); 

请您参考如下方法:

尝试这个:

\bthe\b(?:(?!\bthe\b).)*\blanguage\b 


它使用否定的超前断言来要求在匹配的“ the”和“ language”之间不再看到“ the”。