Using regular expressions in C # to find a duplicate pattern

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: abc
find how many times it appears inabcabcabcabcabc

+3
source share
3 answers

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.

var input = "abcabcabcabcabc";
var pattern = new Regex(@"abc");
var count = pattern.Matches(input).Count;
+5
source
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).

+3
source
Regex.Matches("abcabcabcabcabc", @"abc").Count
+3

All Articles