How to find multiple occurrences with regex groups?

Why does the following code appear:

1 match found for 'the'

and not:

3 matches were found 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(); } } } 
+14
c # regex
Jul 14 2018-10-14T00:
source share
4 answers
 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(); 
+28
Jul 14 '10 at 12:56
source share

Regex.Match (String, String)

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

Use Regex.Matches (String, String) instead.

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

+11
Jul 14 '10 at 12:52
source share

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

Instead, use Matches . Then you can use:

 MatchCollection matches = Regex.Matches(text, search); Console.WriteLine("there were {0} matches", matches.Count); 
+2
Jul 14 '10 at 12:52
source share

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

0
Jul 14 '10 at 12:55
source share



All Articles