How to match multiple results using std::regex
c++, regex
Solution
This can be done in `regex` of `C++11`.
Two methods:
- You can use `()` in `regex` to define your captures(sub expressions).
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
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
Problem
For example, If I have a string like "first second third forth" and I want to match every single word in one operation to output them 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; } ```