代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

我怎么能阻止这个瑞格人贪婪呢?

  •  1
  • Edward Tanguay  · 技术社区  · 15 年前

    当前此regex返回一个匹配项:

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

    我如何才能让它返回两个匹配项:

    最好的语言

    最快的语言

    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("---");
    
    3 回复  |  直到 15 年前
        1
  •  3
  •   Justin user327094    15 年前

    试试这个:

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

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

        2
  •  4
  •   Jay    15 年前

    添加 ? *

        3
  •  0
  •   Toto    15 年前

    这符合你的要求

    /the (?:best|fastest) language/g