views:

40

answers:

1
  boost::regex re;
  re = "(\\d+)";
  boost::cmatch matches;
  if (boost::regex_search("hello 123 world", matches, re))
    {
    printf("Found %s\n", matches[1]); 
    }

Result: "Found 123 world". I just wanted the "123". Is this some problem with null-termination, or just misunderstanding how regex_search works?

+2  A: 

You can't pass matches[1] (an object of type sub_match<T>) to printf like that. The fact that it gives any useful result at all is something you can't count on, since printf expects a char pointer. Instead use:

cout << "Found " << matches[1] << endl;

Or if you want to use printf:

printf("Found %s\n", matches[1].str().c_str());

You can get an std::string object with the result using matches[1].str().

interjay