fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <regex>
  4.  
  5. int main()
  6. {
  7. // Simple regular expression matching
  8. std::string fnames[] = {"foo.txt", "bar.txt", "baz.dat", "zoidberg"};
  9. std::regex txt_regex("[a-z]+\\.txt");
  10.  
  11. for (const auto &fname : fnames) {
  12. std::cout << fname << ": " << std::regex_match(fname, txt_regex) << '\n';
  13. }
  14.  
  15. // Extraction of a sub-match
  16. std::regex base_regex("([a-z]+)\\.txt");
  17. std::smatch base_match;
  18.  
  19. for (const auto &fname : fnames) {
  20. if (std::regex_match(fname, base_match, base_regex)) {
  21. // The first sub_match is the whole string; the next
  22. // sub_match is the first parenthesized expression.
  23. if (base_match.size() == 2) {
  24. std::ssub_match base_sub_match = base_match[1];
  25. std::string base = base_sub_match.str();
  26. std::cout << fname << " has a base of " << base << '\n';
  27. }
  28. }
  29. }
  30.  
  31. // Extraction of several sub-matches
  32. std::regex pieces_regex("([a-z]+)\\.([a-z]+)");
  33. std::smatch pieces_match;
  34.  
  35. for (const auto &fname : fnames) {
  36. if (std::regex_match(fname, pieces_match, pieces_regex)) {
  37. std::cout << fname << '\n';
  38. for (size_t i = 0; i < pieces_match.size(); ++i) {
  39. std::ssub_match sub_match = pieces_match[i];
  40. std::string piece = sub_match.str();
  41. std::cout << " submatch " << i << ": " << piece << '\n';
  42. }
  43. }
  44. }
  45. }
Runtime error #stdin #stdout #stderr 0s 3020KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error