首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在boost匹配结果中查找不匹配

在boost匹配结果中查找不匹配
EN

Stack Overflow用户
提问于 2012-07-04 21:20:01
回答 1查看 538关注 0票数 1

我正在使用boost::regex_match,并试图找到一个函数来获取正则表达式停止匹配的位置。我在boost::match_results对象中找不到任何属性,但有几个使用boost::regex_search显示子匹配的代码片段。我的实现是在正确的道路上,还是我必须做一些不同的事情来实现它?我的代码如下所示:

代码语言:javascript
复制
int main(int args, char** argv)
{
    boost::match_results<std::string::const_iterator> what;

    if(args == 3) 
    {
        std::string text(argv[1]);
        boost::regex expression(argv[2]);

        std::cout << "Text : " << text << std::endl;
        std::cout << "Regex: " << expression << std::endl;

        if(boost::regex_match(text, what, expression, boost::match_default) != 0) 
        {
            int i = 0;

            for(boost::match_results<std::string::const_iterator>::const_iterator it=what.begin(); it!=what.end(); ++it) 
            {
                std::cout << "[" << (i++) << "] " << it->str() << std::endl;
            }
            std::cout << "Matched!" << std::endl;
        } 
        else 
        {
            std::string::const_iterator start = text.begin();
            std::string::const_iterator end   = text.end();

            while(boost::regex_search(start, end, what, expression)) 
            {
                std::string submatch(what[1].first, what[1].second);
                std::cout << submatch << std::endl;
                start = what[0].second;
            }
            std::cout << "Didn't match!" << std::endl;
        }
    } //if(args == 3)
    else 
    {
        std::cout << "Invalid usage! $> ./boost-regex <text> <regex>" << std::endl;
    }
    return 0;
}

输出:

代码语言:javascript
复制
$> ./boost_regex "We're building it up to burn it down" ".*(build.*)(to.*)(burn.*)"
Text : We're building it up to burn it down
Regex: .*(build.*)(to.*)(burn.*)
[0] We're building it up to burn it down
[1] building it up
[2] to
[3] burn it down
Matched!

$> ./boost_regex "We're building it up to burm it down" ".*(build.*)(to.*)(burn.*)"
Text : We're building it up to burm it down
Regex: .*(build.*)(to.*)(burn.*)
Didn't match!

对于最后一个输入,我希望得到类似如下的内容:

代码语言:javascript
复制
Text : We're building it up to burm it down
Regex: .*(build.*)(to.*)(burn.*)
[0] We're building it up to
[1] building it up
[2] to
Didn't match!

先谢谢你...

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-18 10:28:30

首先,您在示例中遇到了正则表达式问题。因为它不能匹配(burn.*)子组,所以整个正则表达式无法匹配任何内容,并且不返回任何结果。添加一个"?“在(burn.*)成功之后,前两个子组将匹配,而第三个子组不匹配。

我想看看rubular.com,它是一个调整正则表达式并实时观察它们工作的很好的工具。

要测试子组是否参与了匹配,需要检查for循环中的sub_match::matched布尔变量,如果子组匹配,则为true。查看boost::submatch here的文档

希望这对我有所帮助,这实际上是我的第一篇Stackoverflow帖子、答案或评论。:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11329931

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档