Delanoy
Delanoy

Reputation: 39

Using Regular Expressions in C# to Find a Recurring Pattern

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

Answers (3)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68707

Regex.Matches("abcabcabcabcabc", @"abc").Count

Upvotes: 3

bdukes
bdukes

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

Josh M.
Josh M.

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

Related Questions