Boost C ++正则表达式-如何返回所有匹配项 [英] Boost C++ regex - how to return all matches

查看:336
本文介绍了Boost C ++正则表达式-如何返回所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串"SolutionAN ANANANA SolutionBN",我想返回所有以Solution开头并以N结尾的字符串.

I have and string "SolutionAN ANANANA SolutionBN" I want to return all string which start with Solution and end with N.

使用正则表达式boost::regex regex("Solu(.*)N"); 我得到的输出为SolutionAN ANANANA SolutionBN.

While using regex boost::regex regex("Solu(.*)N"); I am getting output as SolutionAN ANANANA SolutionBN.

我想以SolutionANSolutionBN的身份离开.我是regex的新手,可以提供任何帮助. 我正在使用的代码段

While I want to get out as SolutionAN and SolutionBN. I am new to regex in boost any help will be appreciated. Snippet if code I am using

#include <boost/regex.hpp>
#include <iostream>

int main(int ac,char* av[])
{
    std::string strTotal("SolutionAN ANANANA SolutionBN");
    boost::regex regex("Solu(.*)N");

    boost::sregex_token_iterator iter(strTotal.begin(), strTotal.end(), regex, 0);
    boost::sregex_token_iterator end;

    for( ; iter != end; ++iter ) {
           std::cout<<*iter<<std::endl;
    }
}

推荐答案

问题是*是贪婪的.更改为使用非贪婪版本(请注意?):

The problem is that * is greedy. Change to using the non-greedy version (note the ?):

int main(int ac,char* av[])
{
    std::string strTotal("SolutionAN ANANANA SolutionBN");
    boost::regex regex("Solu(.*?)N");

    boost::sregex_token_iterator iter(strTotal.begin(), strTotal.end(), regex, 0);
    boost::sregex_token_iterator end;

    for( ; iter != end; ++iter ) {
           std::cout<<*iter<<std::endl;
    }
}

这篇关于Boost C ++正则表达式-如何返回所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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