rahul tyagi rahul tyagi - 1 year ago 93
C++ Question

Regex not working as expected with C++ regex_match

I'm studying regular expressions in c++11 and this regex search is returning false. Does anybody know what I am doing wrong here? . I know that

stands for any number of characters except newlines.

So i was expecting regex_match() to return true and the output to be "found".
However the output is coming out to be "not found".


using namespace std;

int main()
bool found = regex_match("<html>",regex("h.*l"));// works for "<.*>"
cout<<(found?"found":"not found");
return 0;

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download