正则表达式几乎是现代编程语言的标配,现代 C++ 中也提供了正则表达式的原生支持。正则表达式一般用来做字符串的匹配,查询,分割,替换等操作,有时候使用正则表达式比手写解析器要直观方便得多。

🐭 什么是正则表达式

正则表达式是独立自成体系的知识,内容较多,语法也比较繁杂。另外,正则表达式还有不同的流派,比如 awk 流派, grep 流派,ECMAScript 流派等等。
C++ 中的正则表达式可以通过不同的选项来支持不同的正则流派,默认使用的是修改过的 ECMAScript 流派。这里不介绍正则表达式的语法内容,在需要使用的时候,可以查询 C++ 标准文档。

🐂 正则匹配

主要是函数「std::regex_match」,正则匹配是匹配整个模式,部分匹配需要使用正则查询。

  1. #include <iostream>
  2. #include <regex>
  3. #include <string>
  4. int main() {
  5. std::cout.setf(std::ios_base::boolalpha);
  6. const std::string fns[] = {"foo.txt", "baz.dat", "f.o.txt"};
  7. // simple match
  8. const std::regex reg0("[a-z]+\\.txt");
  9. for (const auto &fn : fns) {
  10. std::cout << fn << " matchs the pattern: " << std::regex_match(fn, reg0) << '\n';
  11. }
  12. // foo.txt matchs the pattern: true
  13. // baz.dat matchs the pattern: false
  14. // f.o.txt matchs the pattern: false
  15. // simple search
  16. std::cout << fns[2]
  17. << " matchs the pattern by regex_search: " << std::regex_search(fns[2], reg0)
  18. << '\n';
  19. // f.o.txt matchs the pattern by regex_search: true
  20. // regex_search(data, regex(pattern))
  21. // always equivalent to
  22. // regex_match(data, regex("(.|\n)*"+pattern+"(.|\n)*"))
  23. // group match, group[0] is the whole string
  24. const std::regex reg1("([a-z]+)\\.([a-z]+)");
  25. std::smatch m;
  26. for (const auto &fn : fns) {
  27. if (std::regex_match(fn, m, reg1)) {
  28. for (size_t i = 0; i < m.size(); ++i) {
  29. std::cout << "submatch[" << i << "] = " << m[i].str() << std::endl;
  30. }
  31. std::cout << std::endl;
  32. }
  33. }
  34. #if 0
  35. submatch[0] = foo.txt
  36. submatch[1] = foo
  37. submatch[2] = txt
  38. submatch[0] = baz.dat
  39. submatch[1] = baz
  40. submatch[2] = dat
  41. #endif
  42. return 0;
  43. }

🐯 正则查询

主要是函数「std::regex_search」,正则查询主要用来遍历字符串,查询第一个满足正则模式的匹配结果,找到就退出。基于正则查询的还有两个正则迭代器,支持对字符串不停的进行正则查询,用起来也比较方便。

  1. #include <iostream>
  2. #include <regex>
  3. #include <string>
  4. int main() {
  5. std::string data = "XML tag: <tag-name>the value</tag-name>.";
  6. std::regex reg("<(.*)>(.*)</(\\1)>");
  7. std::smatch m;
  8. if (std::regex_search(data, m, reg)) {
  9. for (size_t i = 0; i < m.size(); ++i) {
  10. std::cout << "m[" << i << "] = " << m[i].str() << std::endl;
  11. }
  12. std::cout << "prefix() = " << m.prefix() << std::endl;
  13. std::cout << "suffix() = " << m.suffix() << std::endl;
  14. }
  15. #if 0
  16. m[0] = <tag-name>the value</tag-name>
  17. m[1] = tag-name
  18. m[2] = the value
  19. m[3] = tag-name
  20. prefix() = XML tag:
  21. suffix() = .
  22. #endif
  23. return 0;
  24. }

图解正则查询:
reg.png
正则迭代器在每次迭代过程中,调用正则查询来得到一个匹配结果。因此,可以在遍历一个字符串的时候多次应用同一个匹配模式。正则分词迭代器用起来就更灵活了,可以指定提取指定部分的匹配结果,也可以指定提取非匹配部分的字符串。

  1. #include <iostream>
  2. #include <regex>
  3. #include <string>
  4. int main() {
  5. const std::string data = "<person>\n"
  6. " <first>Nico</first>\n"
  7. " <last>Josuttis</last>\n"
  8. "</person>\n";
  9. std::regex reg("<(.*)>(.*)</(\\1)>");
  10. std::sregex_iterator beg1(data.cbegin(), data.cend(), reg);
  11. std::sregex_iterator end1;
  12. std::for_each(beg1, end1, [](const std::smatch &m) {
  13. std::cout << m[0].str() << std::endl;
  14. std::cout << m[1].str() << std::endl;
  15. std::cout << m[2].str() << std::endl;
  16. std::cout << m[3].str() << std::endl;
  17. });
  18. #if 0
  19. <first>Nico</first>
  20. first
  21. Nico
  22. first
  23. <last>Josuttis</last>
  24. last
  25. Josuttis
  26. last
  27. #endif
  28. // output is same as above, we can change the {0,1,2,3} to {2} just for values
  29. std::sregex_token_iterator beg2(data.cbegin(), data.cend(), reg, {0, 1, 2, 3});
  30. std::sregex_token_iterator end2;
  31. for (; beg2 != end2; ++beg2) {
  32. std::cout << beg2->str() << std::endl;
  33. }
  34. std::cout << std::endl;
  35. std::string langs = "C, C++ ,Java . Python; Lua";
  36. std::regex sep("[[:space:]]*[,;.][[:space:]]*");
  37. // -1 means non-matched fragment
  38. std::sregex_token_iterator beg3(langs.begin(), langs.end(), sep, -1);
  39. std::sregex_token_iterator end3;
  40. for (; beg3 != end3; ++beg3) {
  41. std::cout << "language: " << beg3->str() << std::endl;
  42. }
  43. std::cout << std::endl;
  44. #if 0
  45. language: C
  46. language: C++
  47. language: Java
  48. language: Python
  49. language: Lua
  50. #endif
  51. return 0;
  52. }

🐰 正则替换

主要是函数「std::regex_replace」,这个函数主要用来迭代字符串的一个个正则匹配结果,然后按照格式化部分指定的要求进行替换,最后拷贝替换后的字符串到输出。与正则捕获组一起使用,能做很多复杂的事情,还要注意匹配选项的合理使用。另外,我们一般不修改原始输入字符串,使用另外一个字符串对象来保存替换后的结果。

  1. #include <iostream>
  2. #include <regex>
  3. #include <string>
  4. int main() {
  5. const std::string data = "<person>\n"
  6. " <first>Nico</first>\n"
  7. " <last>Josuttis</last>\n"
  8. "</person>\n";
  9. std::regex reg("<(.*)>(.*)</(\\1)>");
  10. const std::string repfmt{"<$1 value=\"$2\"/>"};
  11. std::cout << std::regex_replace(data, reg, repfmt) << std::endl;
  12. #if 0
  13. <person>
  14. <first value="Nico"/>
  15. <last value="Josuttis"/>
  16. </person>
  17. #endif
  18. // use iterator interface, and
  19. // - format_no_copy: don’t copy characters that don’t match
  20. // - format_first_only: replace only the first match found
  21. std::string res;
  22. const auto repflags =
  23. std::regex_constants::format_no_copy | std::regex_constants::format_first_only;
  24. std::regex_replace(std::back_inserter(res), data.begin(), data.end(), reg, repfmt,
  25. repflags);
  26. std::cout << res << std::endl;
  27. #if 0
  28. <first value="Nico"/>
  29. #endif
  30. // $& : The matched pattern
  31. // $n : The nth matched capture group
  32. // $` : The prefix of the matched pattern
  33. // $' : The suffix of the matched pattern
  34. // $$ : The character $
  35. std::string text = "Quick brown fOx";
  36. std::regex regvowel("a|e|i|o|u", std::regex_constants::icase);
  37. std::cout << std::regex_replace(text, regvowel, "[$&]") << std::endl;
  38. // Q[u][i]ck br[o]wn f[O]x
  39. return 0;
  40. }