Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match multiple results using std::regex

Tags:

c++

regex

for example.If I have a string like"first second third forth"and I want to match each single word in one operation to output'em one by one.

I just thought that "(\b\S*\b){0,}" would work.But actually it did not.

What should I do?

Here's my code:

#include<iostream> #include<string> using namespace std; int main() {     regex exp("(\\b\\S*\\b)");     smatch res;     string str = "first second third forth";     regex_search(str, res, exp);     cout << res[0] <<" "<<res[1]<<" "<<res[2]<<" "<<res[3]<< endl; }    

I'm looking forward to your kindly help. :)

like image 777
AntiMoron Avatar asked Feb 10 '14 00:02

AntiMoron


1 Answers

Simply iterate over your string while regex_searching, like this:

{     regex exp("(\\b\\S*\\b)");     smatch res;     string str = "first second third forth";      string::const_iterator searchStart( str.cbegin() );     while ( regex_search( searchStart, str.cend(), res, exp ) )     {         cout << ( searchStart == str.cbegin() ? "" : " " ) << res[0];           searchStart = res.suffix().first;     }     cout << endl; } 
like image 66
St0fF Avatar answered Sep 21 '22 18:09

St0fF