Source of greedy_lazy.cpp


  1: //greedy_lazy.cpp

  3: #include <iostream>
  4: using std::cout;
  5: using std::endl;
  6: using std::boolalpha;

  8: #include <string>
  9: using std::string;

 11: #include <regex>
 12: using std::regex;
 13: using std::smatch;

 15: int main()
 16: {
 17:     cout << boolalpha;

 19:     smatch m;

 21:     //First capture captures everything, then "gives back"
 22:     //the .jpg in order to achieve an overall match.
 23:     string pattern1("(.+)(\\.jpg)");
 24:     regex r1(pattern1);
 25:     string data1("filename.jpg");
 26:     cout << regex_match(data1, m, r1) << endl;
 27:     cout << m[0] << "|" << m[1] << "|" << m[2] << "|" << endl;

 29:     //But note that only the minimal amount is "given back", and
 30:     //in the following example that's just the final 6.
 31:     string pattern2("(.*)([0-9]+)");
 32:     regex r2(pattern2);
 33:     string data2("Page 266");
 34:     cout << regex_match(data2, m, r2) << endl;
 35:     cout << m[0] << "|" << m[1] << "|" << m[2] << "|" << endl;

 37:     //If we make the first capture "lazy" by adding a ?, then
 38:     //that capture captures only the minimal amount before turning
 39:     //things over to the next part of the regex.
 40:     string pattern3("(.*?)([0-9]+)");
 41:     regex r3(pattern3);
 42:     string data3("Page 266");
 43:     cout << regex_match(data3, m, r3) << endl;
 44:     cout << m[0] << "|" << m[1] << "|" << m[2] << "|" << endl;
 45: }

 47: /*Output:
 48: true
 49: filename.jpg|filename|.jpg|
 50: true
 51: Page 266|Page 26|6|
 52: true
 53: Page 266|Page |266|
 54: */