Regex not working as expected with C ++ regex_match

I am learning regular expressions in C ++ 11, and this regular expression search returns false. Does anyone know what I'm 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 would be found. However, the output is "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; } 
+6
source share
1 answer

You need to use regex_search , not regex_match :

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

See the IDEONE demo

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

The regex_match documentation says:

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

regex_search is different:

Returns whether any subsequence in the target sequence (subject) rgx regular expression (pattern).

+11
source

Source: https://habr.com/ru/post/989927/


All Articles