Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find multiple occurrences with regex groups?

Tags:

c#

regex

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();         }     } } 
like image 835
Edward Tanguay Avatar asked Jul 14 '10 12:07

Edward Tanguay


People also ask

How do you find multiple occurrences of a string in regex?

Method 1: Regex re. To get all occurrences of a pattern in a given string, you can use the regular expression method re. finditer(pattern, string) . The result is an iterable of match objects—you can retrieve the indices of the match using the match.

Can you count with regex?

To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.


1 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(); 
like image 107
Draco Ater Avatar answered Oct 05 '22 23:10

Draco Ater