当前位置:   article > 正文

正则表达式匹配字符串_std::regex如何匹配某个指定的字符串

std::regex如何匹配某个指定的字符串
  1. /*1 正则表达式 搜索6位数 */
  2. std::string aa = "072007P44";
  3. std::string bb = "072007 P44";
  4. std::regex pattern("([0-9]{6})");
  5. std::smatch matches;
  6. if (std::regex_search(aa, matches, pattern)) {
  7. std::string result = matches[1].str();
  8. std::cout << aa << std::endl;
  9. std::cout << result << std::endl;/* 072007 */
  10. }
  11. else {
  12. std::cout << "No match found." << std::endl;
  13. }
  14. if (std::regex_search(bb, matches, pattern)) {
  15. std::string result = matches[1].str();
  16. std::cout << bb << std::endl;
  17. std::cout << result << std::endl;/* 072007 */
  18. }
  19. else {
  20. std::cout << "No match found." << std::endl;
  21. }
  22. // 2
  23. std::string aa = "CTD220162_1_KSZJ_008-REV01";
  24. std::regex pattern("[_-]([A-Z]+[_-][0-9]+)[_-]");
  25. std::smatch matches;
  26. if (std::regex_search(aa, matches, pattern)) {
  27. std::string result = matches[1].str();
  28. std::cout << result << std::endl; // KSZJ_008
  29. }
  30. else {
  31. std::cout << "No match found." << std::endl;
  32. }
  33. // 3 找6位字符串
  34. vector<string> GetRegexString(const string& cstr) {
  35. smatch matches;
  36. vector<string> cstrs;
  37. regex x("^.*([_-](([1-9]|[a-z]|[A-Z]){6})[_-]).*$"); // tak2500446_123456_tra
  38. if (regex_search(cstr, matches, x))
  39. cstrs.push_back(matches[1]), // _123456_
  40. cstrs.push_back(matches[2]);//123456
  41. return cstrs;
  42. }
  43. // 4 找7位字符串
  44. vector<string> GetRegexString_a(const string& cstr) {
  45. smatch matches;
  46. vector<string> cstrs;
  47. regex x("^.*([_-](([1-9]|[a-z]|[A-Z]){7})[_-]).*$");// tak2500446_123456A_tra
  48. if (regex_search(cstr, matches, x))
  49. cstrs.push_back(matches[1]),// _123456A_
  50. cstrs.push_back(matches[2]);//123456
  51. return cstrs;
  52. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/113484
推荐阅读
相关标签
  

闽ICP备14008679号