【问题标题】:Boost C++ regex - how to get multiple matchesBoost C++ 正则表达式 - 如何获得多个匹配项
【发布时间】:2011-03-08 12:46:02
【问题描述】:

如果我有一个简单的正则表达式模式,比如“ab”。我有一个字符串,它有多个匹配项,例如“abc abd”。如果我执行以下操作...

boost::match_flag_type flags = boost::match_default;
boost::cmatch mcMatch;
boost::regex_search("abc abd", mcMatch, "ab.", flags)

然后 mcMatch 只包含第一个“abc”结果。如何获得所有可能的匹配项?

【问题讨论】:

    标签: c++ regex boost


    【解决方案1】:

    您可以在这个简短的示例中使用boost::sregex_token_iterator

    #include <boost/regex.hpp>
    #include <iostream>
    #include <string>
    
    int main() {
        std::string text("abc abd");
        boost::regex regex("ab.");
    
        boost::sregex_token_iterator iter(text.begin(), text.end(), regex, 0);
        boost::sregex_token_iterator end;
    
        for( ; iter != end; ++iter ) {
            std::cout<<*iter<<'\n';
        }
    
        return 0;
    }
    

    这个程序的输出是:

    abc
    abd
    

    【讨论】:

    • 感谢您的快速回复。问题, *iter 返回什么,在我的快速测试中它似乎不是 boost::cmatch ?我只是举了一个非常简单的例子。在我的正则表达式中,我可能有组,所以我需要访问每场比赛的组信息(可从 cmatch 获得)?
    • 您可以尝试使用 regex_iterator,它会在取消引用时返回 match_result,并且应该为您提供所需的内容?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多