AntiMoron AntiMoron - 3 months ago 16
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:

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

Answer

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

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

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

Comments