How to use C # and regular expressions to find how many times a pattern occurs in a string or if the pattern repeats throughout the string. For instance:
Pattern: abcfind how many times it appears inabcabcabcabcabc
abc
abcabcabcabcabc
You can use method Matchesc Regexto get all matches in a given input string for a given pattern. If the pattern you match is a user, you probably also want to use Regex.Escapeto avoid any special characters in it.
Matches
Regex
Regex.Escape
var input = "abcabcabcabcabc"; var pattern = new Regex(@"abc"); var count = pattern.Matches(input).Count;
int count = Regex.Matches("abcabcabcabcabc", "abc").Count;
This will return the number of occurrences of the template (parameter 2) in the search text (parameter 1).
Regex.Matches("abcabcabcabcabc", @"abc").Count