Reputation: 29397
I can't find working code for that, managed only to coin up this snippet, it compiles but gives wrong output.
#include <string>
#include <iostream>
#include <boost/regex.hpp>
int main() {
using namespace std;
string input = "123 apples 456 oranges 789 bananas oranges bananas";
boost::regex re = boost::regex("[a-z]+");
boost::match_results<string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
string::const_iterator s = input.begin();
string::const_iterator e = input.end();
while (boost::regex_search(s,e,what,re,flags)){
cout << what.position() << ", ";
string::difference_type l = what.length();
string::difference_type p = what.position();
s += p + l;
}
}
output is: 4, 5, 5, 1, 1,
but should be: 4, 15, 27, 35, 43,
Upvotes: 1
Views: 143
Reputation: 1283
You're almost right, but failing to account for the fact that cout << what.position() << ", ";
will output the matching string's position relative to the end of the last matching string, ie s
.
Since s
knows exactly where it is in relation to input
, this should work:
cout << ((s - input.begin()) + what.position()) << ", ";
Upvotes: 2