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

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

问题描述

例如。如果我有一个字符串像第二第三第三,并且我想在一个操作中匹配每个单个字,一个一个输出。

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.

我只是想(\b\S * \b){0,}会工作。但实际上它没有。 / strong>

I just thought that "(\b\S*\b){0,}" would work.But actually it did not.

我该怎么办?

/ p>

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

我期待着您的亲切帮助。 :)

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

推荐答案

这可以在 regex C ++ 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

您可以使用 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

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

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