Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last match with Boost::Regex

Tags:

c++

regex

boost

I have a regular expression in C++ with Boost which matches lines in multi-line strings. Regex search finds the first match, however I'm interested in the last line which matches.

The code I'm using now is something like this:

matched = boost::regex_search(input, results, regex);               
if (!matched) {
    return -1; // error code
}
matched_string = results["Group"]; 

If regex was "(?<Group>Data.)" and input was "Data1 Data2 Data3", then matched_string is now "Data1". I want it to be "Data3".

like image 327
Felix Dombek Avatar asked Feb 28 '11 11:02

Felix Dombek


1 Answers

operator[] of match_results returns a sub_match. sub_match inherits std::pair of iterators. Its first and second members correspond to matched range. So, you can use its second for start point of new search. For example:

string  input = "Data1 Data2 Data3";
regex  re("(?<Group>Data.)");
string::const_iterator  begin = input.begin(), end = input.end();
smatch  results;
while ( regex_search( begin, end, results, re ) ) {
  smatch::value_type  r = results["Group"];
  begin = r.second;
}

Hope this helps.

like image 172
Ise Wisteria Avatar answered Sep 24 '22 16:09

Ise Wisteria