36

Why does the following code result in:

there was 1 matches for 'the'

and not:

there was 3 matches for 'the'

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();
        }
    }
}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

4 Answers4

61
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();
Draco Ater
  • 20,820
  • 8
  • 62
  • 86
21

Regex.Match(String, String)

Searches the specified input string for the first occurrence of the specified regular expression.

Use Regex.Matches(String, String) instead.

Searches the specified input string for all occurrences of a specified regular expression.

Amarghosh
  • 58,710
  • 11
  • 92
  • 121
7

Match returns the first match, see this for how to get the rest.

You should use Matches instead. Then you could use:

MatchCollection matches = Regex.Matches(text, search);
Console.WriteLine("there were {0} matches", matches.Count);
Lazarus
  • 41,906
  • 4
  • 43
  • 54
3

You should be using Regex.Matches instead of Regex.Match if you want to return multiple matches.

TheQ
  • 508
  • 5
  • 15