Here is an excerpt from Finding All Regex Matches at regular-expressions.info:
Construct one object by calling the constructor with three parameters: a string iterator indicating the starting position of the search, a string iterator indicating the ending position of the search, and the regex object. If there are any matches to be found, the object will hold the first match when constructed. Construct another iterator object using the default constructor to get an end-of-sequence iterator. You can compare the first object to the second to determine whether there are any further matches. As long as the first object is not equal to the second, you can dereference the first object to get a match_results
object.
So, you can use the following to get matches and their positions:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main() {
std::regex r(R"(\w)");
std::string s("a,b,c,d,e,f,g");
for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
i != std::sregex_iterator();
++i)
{
std::smatch m = *i;
std::cout << "Match value: " << m.str() << " at Position " << m.position() << '\n';
}
return 0;
}
See the IDEONE demo
Results:
Match value: a at Position 0
Match value: b at Position 2
Match value: c at Position 4
Match value: d at Position 6
Match value: e at Position 8
Match value: f at Position 10
Match value: g at Position 12
The regex is better declared with a raw string literal (R"(\w)"
is a \w
regex pattern).