如何使用std :: regex匹配多个结果

例如,如果我有一个字符串,例如“ first second second third”,并且我想在一个操作中匹配每个单词以一个一个地输出它们。


我只是认为“(\ b \ S * \ b){0,}”可以工作。但是实际上没有。


我该怎么办?


这是我的代码:


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

}   

期待您的帮助。:)


慕桂英546537
浏览 1475回答 3
3回答

慕运维8079593

您可以使用suffix()函数,然后再次搜索直到找不到匹配项:int main(){&nbsp; &nbsp; regex exp("(\\b\\S*\\b)");&nbsp; &nbsp; smatch res;&nbsp; &nbsp; string str = "first second third forth";&nbsp; &nbsp; while (regex_search(str, res, exp)) {&nbsp; &nbsp; &nbsp; &nbsp; cout << res[0] << endl;&nbsp; &nbsp; &nbsp; &nbsp; str = res.suffix();&nbsp; &nbsp; }}&nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP