2011-06-26 65 views
1

我想匹配升压一个简单的表达,但它的行为奇怪...下面的代码应匹配,并显示“A”从第一和第二串:boost xpressive:错误的匹配?

#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 

回答

1

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

请参阅该文档:sub_matchmatch_resultsregex_match

+0

小测试结果;那些都OK:'cout <<什么[1] << endl; printf(“%s \ n”,what [1] .str()。c_str()); printf(“%s \ n”,string(what [1])。c_str());'This is not:'printf(“%s \ n”,what [1]);'' –

0

在正则表达式删除各地\方括号W和使用std ::法院进行打印。然后你会得到你想要的结果。