views:

122

answers:

1
+2  Q: 

Boost.Regex oddity

Hi, Does anyone have any idea why the following code would output "no match"?

  boost::regex r(".*\\.");
  std::string s("app.test");
  if (boost::regex_match(s, r))
    std::cout << "match" << std::endl;
  else
    std::cout << "no match" << std::endl;
+5  A: 

I believe regex_match() matches against the entire string. Try regex_search() instead.

It would have worked with the following regex:

boost::regex r(".*\\..*");

and the regex_match() function. But again, regex_search() is what you're probably looking for.

Bart Kiers
+1 - "Determines whether there is an exact match between the regular expression e, and all of the character sequence". See http://www.boost.org/doc/libs/1_40_0/libs/regex/doc/html/boost_regex/ref/regex_match.html
Dominic Rodger
Though I think he really wants `regex_search()`.
Dominic Rodger
Indeed, that was it.I feel kind of stupid now.Still, thank's for the answer
ldx
@ldx - if it's any consolation, I got confused by the *exact* same thing today, in my case wondering why a `regex_match` was working when it looked like it ought to need a `^` at the beginning and a `$` at the end.
Dominic Rodger
@Dominic: yes, I can understand the confusion. In Java, String.matches() does exactly the same but PHP's preg_match() for example just looks for an occurrence of the regex similar to Boost's regex_search().
Bart Kiers