Reputation: 39
How would I use C# and regular expressions to find how many times a pattern occurs in a string or if a pattern is repeated throughout the entire string. For example:
Pattern: abc
find how many times this appears in abcabcabcabcabc
Upvotes: 3
Views: 696
Reputation: 156005
You can use the Matches
method off the Regex
class to get all of the matches in a given input string for a given pattern. If the pattern that you're matching on is user input, you probably also want to use Regex.Escape
to escape any special characters in it.
var input = "abcabcabcabcabc";
var pattern = new Regex(@"abc");
var count = pattern.Matches(input).Count;
Upvotes: 5
Reputation: 27811
int count = Regex.Matches("abcabcabcabcabc", "abc").Count;
This will return the number of occurrences of the pattern (parameter 2) within the text to search (parameter 1).
Upvotes: 3