c++ regex count number of matches
Here is an example of how you can count the number of matches using regular expressions in C++:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "Hello, this is a sample text with some numbers: 12345, 67890, and 54321.";
std::regex pattern("\\d+"); // Match one or more digits
std::sregex_iterator it(text.begin(), text.end(), pattern);
std::sregex_iterator end;
int count = 0;
while (it != end) {
++count;
++it;
}
std::cout << "Number of matches: " << count << std::endl;
return 0;
}
Let's go through the steps:
- Include the necessary headers:
<iostream>
for input/output operations<regex>
for regular expressions<string>
for working with strings.Declare a
main
function, which is the entry point of your program.Create a string variable
text
that contains the text you want to search for matches. In this example, we have the text "Hello, this is a sample text with some numbers: 12345, 67890, and 54321."Create a regular expression pattern using the
std::regex
class. In this example, the pattern is "\d+", which matches one or more digits.Create a
std::sregex_iterator
objectit
using thestd::sregex_iterator
constructor. The constructor takes three parameters: the beginning iterator of the text, the end iterator of the text, and the regular expression pattern.Create another
std::sregex_iterator
objectend
to represent the end of the iteration.Initialize a variable
count
to keep track of the number of matches found.Use a
while
loop to iterate over the matches. In each iteration, increment thecount
variable and theit
iterator.After the loop ends, output the value of
count
usingstd::cout
.Finally, return 0 to indicate successful program execution.
This program will output "Number of matches: X" where X is the number of matches found in the text. In this example, it will output "Number of matches: 3" because there are three numbers (12345, 67890, and 54321) in the text that match the pattern "\d+".