Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between regex_match and regex_search?

Tags:

c++

regex

gcc

g++

I was experimenting with regular expression in trying to make an answer to this question, and found that while regex_match finds a match, regex_search does not.

The following program was compiled with g++ 4.7.1:

#include <regex> #include <iostream>  int main() {     const std::string s = "/home/toto/FILE_mysymbol_EVENT.DAT";     std::regex rgx(".*FILE_(.+)_EVENT\\.DAT.*");     std::smatch match;      if (std::regex_match(s.begin(), s.end(), rgx))         std::cout << "regex_match: match\n";     else         std::cout << "regex_match: no match\n";      if (std::regex_search(s.begin(), s.end(), match, rgx))         std::cout << "regex_search: match\n";     else         std::cout << "regex_search: no match\n"; } 

Output:

 regex_match: match regex_search: no match 

Is my assumption that both should match wrong, or might there a problem with the library in GCC 4.7.1?

like image 209
Some programmer dude Avatar asked Jul 24 '12 09:07

Some programmer dude


1 Answers

Assuming that C++ and Boost Regex have a similar structure and functionality, the difference between regex_match and regex_search is explained here:

The regex_match() algorithm will only report success if the regex matches the whole input, from beginning to end. If the regex matches only a part of the input, regex_match() will return false. If you want to search through the string looking for sub-strings that the regex matches, use the regex_search() algorithm.

like image 154
Yan Foto Avatar answered Sep 19 '22 07:09

Yan Foto