提升xpressive:错误匹配?

时间:2011-06-26 02:00:05

标签: c++ regex boost boost-regex

我希望将一个简单的表达式与 boost 匹配,但它表现得很奇怪......下面的代码应匹配并显示第一个和第二个字符串中的“a”:

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

#include "stdio.h"

using namespace boost::xpressive;

void xmatch_action( const char *line ) {
    cregex g_re_var;
    cmatch what;
    g_re_var = cregex::compile( "\\s*var\\s+([\\w]+)\\s*=.*?" );


    if (regex_match(line, what, g_re_var )) {
        printf("OK\n");
        printf(">%s<\n", what[1] );
    }
    else {
        printf("NOK\n");
    }
}

int main()
{
    xmatch_action("var a = qqq");
    xmatch_action(" var a = aaa");
    xmatch_action(" var abc ");
}

但我的实际输出是:

OK
>a = qqq<
OK
>a = aaa<
NOK

它应该是

OK
>a<
OK
>a<
NOK

2 个答案:

答案 0 :(得分:1)

而不是printf()使用<<运算符来打印sub_match对象(what[1])。或者,您可以尝试使用what[1].str()代替what[1]

请参阅文档:sub_matchmatch_resultsregex_match

答案 1 :(得分:0)

在正则表达式中删除\ w周围的方括号并使用std :: cout进行打印。然后你会得到你想要的结果。