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

如何使用regex组查找多个匹配项?

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

    为什么以下代码会导致:

    “the”有1场比赛

    而不是:

    “the”有3场比赛

    using System;
    using System.Text.RegularExpressions;
    
    namespace TestRegex82723223
    {
        class Program
        {
            static void Main(string[] args)
            {
                string text = "C# is the best language there is in the world.";
                string search = "the";
                Match match = Regex.Match(text, search);
                Console.WriteLine("there was {0} matches for '{1}'", match.Groups.Count, match.Value);
                Console.ReadLine();
            }
        }
    }
    
    4 回复  |  直到 7 年前
        1
  •  40
  •   Draco Ater    15 年前
    string text = "C# is the best language there is in the world.";
    string search = "the";
    MatchCollection matches = Regex.Matches(text, search);
    Console.WriteLine("there was {0} matches for '{1}'", matches.Count, search);
    Console.ReadLine();
    
        2
  •  14
  •   Amarghosh    15 年前

    Regex.Match(String, String)

    在指定的输入字符串中搜索指定正则表达式的第一个匹配项。

    使用 Regex.Matches(String, String) 相反。

    在指定的输入字符串中搜索指定正则表达式的所有匹配项。

        3
  •  4
  •   Lazarus    15 年前

    Match 返回 第一 匹配,见 this 如何得到其余的。

    你应该使用 Matches 相反。然后你可以使用:

    MatchCollection matches = Regex.Matches(text, search);
    Console.WriteLine("there were {0} matches", matches.Count);
    
        4
  •  3
  •   TheQ    15 年前

    你应该用 Regex.Matches 而不是 Regex.Match 如果要返回多个匹配项。