【问题标题】:Boost C++ regex - how to return all matchesBoost C++ 正则表达式 - 如何返回所有匹配项
【发布时间】:2013-05-21 09:01:07
【问题描述】:

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

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

虽然我想以SolutionANSolutionBN 的身份退出。我是正则表达式的新手,任何帮助都将不胜感激。 如果我正在使用代码片段

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

【问题讨论】:

    标签: c++ regex boost


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢,我对正则表达式还有一个疑问,假设我输入了 SolutionAN ANANANA SolutionBN abc abc Solution 。我想获取所有以 SOlu 开头并在下一个 Solu 开始的位置结束的字符串,例如输入:SolutionAN ANANANA SolutionBN abc abc 解决方案输出:3 个不同的字符串 SolutionAN ANANANA SolutionBN abc abc 解决方案
    • 如果我需要迭代并只获取一个捕获组(而不是整个匹配模式)怎么办?
    猜你喜欢
    • 2021-10-12
    • 2020-12-02
    • 1970-01-01
    • 2018-02-18
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    相关资源
    最近更新 更多