Counting Regex Matches

How can you count the number of matches found in a string using regex?

Counting the number of regex matches in a string can be accomplished using std::sregex_iterator. This iterator allows you to iterate through all matches of a regex pattern in a string.

Using std::sregex_iterator

Here's a simple example of how to count matches:

#include <iostream>
#include <regex>

int main() {
  std::string input = "one two three four five";
  std::regex pattern("\\b\\w+\\b");

  auto words_begin = std::sregex_iterator(
    input.begin(), input.end(), pattern);
  auto words_end = std::sregex_iterator();

  int count = std::distance(words_begin, words_end);
  std::cout << "Number of words: " << count;
}
Number of words: 5

In this example, the regex pattern "\b\w+\b" matches individual words in the string. We use std::sregex_iterator to iterate through all matches and std::distance to count them.

Detailed Example

Here's another example that counts specific patterns, such as digits:

#include <iostream>
#include <regex>

int main() {
  std::string input =
    "There are 3 cats, 4 dogs, and 5 birds.";
  std::regex pattern("\\d");

  auto numbers_begin = std::sregex_iterator(
    input.begin(), input.end(), pattern);
  auto numbers_end = std::sregex_iterator();

  int count = std::distance(
    numbers_begin, numbers_end);
  std::cout << "Number of digits: " << count;
}
Number of digits: 3

In this case, the regex pattern "\d" matches individual digits. The process is the same: create an iterator for the matches and use std::distance to count them.

Summary

Counting regex matches in a string is straightforward with std::sregex_iterator. This iterator provides a way to traverse all matches of a pattern, and std::distance helps count them. This method is efficient and works well for both simple and complex patterns.

Regex Capture Groups

An introduction to regular expression capture groups, and how to use them in C++ with regex_search, regex_replace, regex_iterator, and regex_token_iterator

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Greedy vs Lazy Quantifiers
What are the differences between greedy and lazy quantifiers in regex?
Non-Capture Groups
What are non-capture groups and when should they be used?
Regex Replace in C++
How do you replace text in a string using regex in C++?
Splitting Strings with Regex
Can regex be used to split strings in C++?
Using Backreferences in Regex
How do you use backreferences in C++ regex?
Formatting Dates with Regex
How can you use regex to format dates in C++?
Lookahead and Lookbehind
What are lookahead and lookbehind assertions in regex?
Third-Party Regex Libraries
Are there any recommended third-party libraries for working with regex in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant