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(); } } }
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With