rahul tyagi rahul tyagi - 11 days ago 5
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".

#include<regex>
#include<iostream>

using namespace std;

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

Answer

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