AntiMoron AntiMoron - 10 months ago 53
C++ Question

How to match multiple results using std::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:

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. :)


This can be done in regex of C++11.

Two methos:

  1. You can use () in regex to define your captures.

    Like this:

    string var = "first second third forth";
    const regex r("(.*) (.*) (.*) (.*)");  
    smatch sm;
    if (regex_search(var, sm, r))
        for (int i=1; i<sm.size(); i++)
            cout << sm[i] << endl;

    See it live:

  2. You can use sregex_token_iterator():

    string var = "first second third forth";
    regex wsaq_re("\\s+"); 
    copy( sregex_token_iterator(var.begin(), var.end(), wsaq_re, -1),
        ostream_iterator<string>(cout, "\n"));

    See it live: