Regex not working as expected with C++ regex_match

You need to use a regex_search rather than regex_match:

bool found = regex_search("<html>",regex("h.*l"));

See IDEONE demo

In plain words, regex_search will search for a substring at any position in the given string. regex_match will only return true if the entire input string is matched (same behavior as matches in Java).

The regex_match documentation says:

Returns whether the target sequence matches the regular expression rgx.
The entire target sequence must match the regular expression for this function >to return true (i.e., without any additional characters before or after the >match). For a function that returns true when the match is only part of the >sequence, see regex_search.

The regex_search is different:

Returns whether some sub-sequence in the target sequence (the subject) matches the regular expression rgx (the pattern).

Leave a Comment