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.
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.
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.
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.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to regular expression capture groups, and how to use them in C++ with regex search
, replace
, iterator
, and token_iterator