3

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

5
  • 1
    I think regex is a bit of overkill. And will you already know the "originating pattern", you do you plan to discover that? Commented Mar 22, 2011 at 14:43
  • 1
    I think this is a simple example. Perhaps the real case is more complex. Also, it is very simple to do this with regular expressions so I'm not sure how it's "overkill." People seem to have a general aversion to using regular expressions! Commented Mar 22, 2011 at 14:46
  • 1
    @Josh M. "People seem to have a general aversion to using regular expressions!" For good reason. Commented Mar 22, 2011 at 14:48
  • @Yuriy - go on...don't be scared. You still loop through each character in a string just to extract the information, huh? Commented Mar 22, 2011 at 15:09
  • @Josh M. I've recently come across a 500+ character regex written in one line without any comments. I've since rewritten the solution with my own regex using a good amount of comments and multiple lines and maybe in the end 50 characters. Surprisingly the original regex didn't even work. Commented Mar 22, 2011 at 15:13

3 Answers 3

5

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;
Sign up to request clarification or add additional context in comments.

Comments

3
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).

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.