Skip to content

Instantly share code, notes, and snippets.

@vpetrigo
Created November 30, 2015 20:54
Show Gist options
  • Save vpetrigo/31d16f872f4605060ffd to your computer and use it in GitHub Desktop.
Save vpetrigo/31d16f872f4605060ffd to your computer and use it in GitHub Desktop.
C++ regex difference between regex_search and regex_match
#include <regex>
#include <iostream>
#include <string>
using namespace std;
class RegExpSearch {
public:
static std::smatch check_string(const std::regex &re, const std::string &s) {
std::smatch matches;
std::regex_search(s, matches, re);
return matches;
}
};
class RegExpMatch {
public:
static std::smatch check_string(const std::regex &re, const std::string &s) {
std::smatch matches;
std::regex_match(s, matches, re);
return matches;
}
};
int main() {
string user_pattern;
regex pattern;
cout << "enter the pattern: ";
getline(cin, user_pattern);
try {
pattern = user_pattern;
}
catch (std::regex_error &e) {
cout << user_pattern << " is a wrong pattern" << endl;
return 1;
}
cout << "enter lines to search in: ";
for (string line; getline(cin, line); ) {
// Change here the RegExpSearch to RegExpMatch and vice versa to understand the difference
auto m = RegExpSearch::check_string(pattern, line);
if (!m.empty()) {
for (auto i = 0; i < m.size(); ++i) {
cout << "match[" << i << "]: " << m[i] << endl;
}
}
else {
cout << "didn't match" << endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment