How to match multiple results using std::regex

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;
}

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: http://coliru.stacked-crooked.com/a/e1447c4cff9ea3e7

  1. 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),
         sregex_token_iterator(),
         ostream_iterator<string>(cout, "\n"));
    

See it live: http://coliru.stacked-crooked.com/a/677aa6f0bb0612f0


You could use the suffix() function, and search again until you don't find a match:

int main()
{
    regex exp("(\\b\\S*\\b)");
    smatch res;
    string str = "first second third forth";

    while (regex_search(str, res, exp)) {
        cout << res[0] << endl;
        str = res.suffix();
    }
}   

Tags:

C++

Regex