Reputation: 199
Below is the code to find the match of "\b(sub)([^ ]*)" in "this subject has a submarine as a subsequence". But I also want to know the position of those sub matches in original string by regex_token_iterator itself. The result should be 5, 19, 34.
// regex_token_iterator example
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("this subject has a submarine as a subsequence");
std::regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub"
// default constructor = end-of-sequence:
std::regex_token_iterator<std::string::iterator> rend;
std::cout << "entire matches:";
std::regex_token_iterator<std::string::iterator> a ( s.begin(), s.end(), e );
while (a!=rend) std::cout << " [" << *a++ << "]";
std::cout << std::endl;
return 0;
}
Output:
entire amtches: [subject] [submarine] [subsequence]
Upvotes: 3
Views: 2433
Reputation: 1768
*a
return a pair of two iterators over the string s. You could try this:
std::cout << " [" << *a++ << ' ' << a->first - s.begin() << "]";
or this
std::cout << " [" << *a++ << ' ' << std::distance(s.begin(), a->first) << "]";
Upvotes: 6