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

2021-12-03 00:00:00 regex c++

例如.如果我有一个像first second third Fifth"这样的字符串,并且我想在一个操作中匹配每个单词以一个一个地输出它们.

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.

我只是认为(S*){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;
}   

我期待着您的帮助.:)

I'm looking forward to your kindly help. :)

推荐答案

这可以在C++11regex中完成.

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

两种方法:

  1. 您可以在 regex 中使用 () 来定义您的捕获.
  1. You can use () in regex to define your captures.

像这样:

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

现场观看:http://coliru.stacked-crooked.com/a/e1447c4cff9ea3e7

  1. 你可以使用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, "
"));

现场观看:http://coliru.stacked-crooked.com/a/677aa6f0bb0612f0

相关文章