C++ STL之正则表达式详解一、用法速查#includeregex#includeiostream#includestringintmain(){// ===== 基础匹配 =====std::regexre(R"(\d+)");std::string s="hello 42 world";// regex_match: 必须完全匹配整个序列if(std::regex_match(s,re))std::cout"匹配\n";// 不会执行// regex_search: 部分匹配,找到第一个子串即可if(std::regex_search(s,re))std::cout"包含数字\n";// 输出// ===== 捕获组 =====std::regexre2(R"((\w+)@(\w+\.\w+))");std::smatch m;std::string email="user@example.com";if(std::regex_match(email,m,re2)){std::cout"完整: "m[0]"\n";// user@example.comstd::cout"用户: "m[1]"\n";// userstd::cout"域名: "m[2]"\n";// example.com}// ===== regex_replace =====std::string text="id: 42, price: 99";std::regexre3(R"(\d+)");std::string out=std::regex_replace(text,re3,"[$]");// 输出: id: [42], price: [99]std::coutout"\n";// 用捕获组重排: $1 $2 引用std::regexre4(R"((\w+),\s*(\w+))");std::string names="Doe, John";std::string swapped=std::regex_replace(names,re4,"$2 $1");std::coutswapped"\n";// John Doe}二、底层原理2.1 ECMAScript 语法子集(默认语法)C++std::regex默认使用ECMAScript 语法,若不指定std::regex::flag_type则等价于std::regex::ECMAScript。支持的语法子集包括:特性语法说明字符类\d\w\s\D\W\S数字/单词/空白及取反量词*+?{n,m}{n,}默认贪婪,后缀?变为非贪婪分组(...)捕获组(?:...)非捕获组字符集[abc][a-z][^abc]字符集合与取反锚点^$\b\B行首/行尾/单词边界选择|多分支选择反向引用\1\2匹配前面对应捕获组的内容不支持的特性:Lookahead/lookbehind(零宽断言)、命名捕获组(?name)、原子分组(?...)等 ECMAScript 2018+ 语法。2.2 regex_match vs regex_search vs regex_replace