开发者

boost xpressive: wrong match?

开发者 https://www.devze.com 2023-03-15 16:08 出处:网络
I want to match a simple expression with boost, but it behaves strange... The code below should match and display \"a\" from first and second strings:

I want to match a simple expression with boost, but it behaves strange... The code below should match and display "a" from first and second strings:

#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\开发者_如何学Go\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 ");
}

but my actual output is:

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

and it should be

OK
>a<
OK
>a<
NOK


Instead of printf() use the << operator to print the sub_match object (what[1]). Or you can try using what[1].str() instead of what[1].

See the docs: sub_match, match_results, regex_match


Remove square brackets around \w in regex AND use std::cout for printing. Then you will get result that you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号