如何使用 std::regex 匹配多个结果 [英] How to match multiple results using std::regex

查看:41
本文介绍了如何使用 std::regex 匹配多个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如.如果我有一个像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

这篇关于如何使用 std::regex 匹配多个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆