1

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\\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
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

2 Answers2

1

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

Qtax
  • 33,241
  • 9
  • 83
  • 121
  • results of a small test; those are OK: `cout << what[1] << endl; printf("%s\n", what[1].str().c_str() ); printf("%s\n", string(what[1]).c_str() );` This is not OK: `printf("%s\n", what[1] );` – Jakub M. Jun 26 '11 at 10:01
0

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

Leonid Volnitsky
  • 8,854
  • 5
  • 38
  • 53