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

新手上路,请多包涵

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

我只是认为 "(\\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;
}

原文由 AntiMoron 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

这可以在 regexC++11 中完成。

两种方法:

  1. 您可以在 () regex 来定义您的捕获。

像这样:

     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, "\n"));

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

原文由 herohuyongtao 发布,翻译遵循 CC BY-SA 4.0 许可协议

sregex_token_iterator 似乎是理想、有效的解决方案,但所选答案中给出的示例还有很多不足之处。相反,我在这里找到了一些很好的例子: http ://www.cplusplus.com/reference/regex/regex_token_iterator/regex_token_iterator/

为了您的方便,我复制粘贴了该页面显示的示例代码。我不认为代码的功劳。

 // regex_token_iterator example
#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("this subject has a submarine as a subsequence");
  std::regex e ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"

  // default constructor = end-of-sequence:
  std::regex_token_iterator<std::string::iterator> rend;

  std::cout << "entire matches:";
  std::regex_token_iterator<std::string::iterator> a ( s.begin(), s.end(), e );
  while (a!=rend) std::cout << " [" << *a++ << "]";
  std::cout << std::endl;

  std::cout << "2nd submatches:";
  std::regex_token_iterator<std::string::iterator> b ( s.begin(), s.end(), e, 2 );
  while (b!=rend) std::cout << " [" << *b++ << "]";
  std::cout << std::endl;

  std::cout << "1st and 2nd submatches:";
  int submatches[] = { 1, 2 };
  std::regex_token_iterator<std::string::iterator> c ( s.begin(), s.end(), e, submatches );
  while (c!=rend) std::cout << " [" << *c++ << "]";
  std::cout << std::endl;

  std::cout << "matches as splitters:";
  std::regex_token_iterator<std::string::iterator> d ( s.begin(), s.end(), e, -1 );
  while (d!=rend) std::cout << " [" << *d++ << "]";
  std::cout << std::endl;

  return 0;
}

Output:
entire matches: [subject] [submarine] [subsequence]
2nd submatches: [ject] [marine] [sequence]
1st and 2nd submatches: [sub] [ject] [sub] [marine] [sub] [sequence]
matches as splitters: [this ] [ has a ] [ as a ]

原文由 Steven 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题