C++ <regex>
系统讲解 C++11 正则表达式库 <regex> 的反斜杠转义与原始字符串字面量、核心类与算法(regex_match/search/replace/sregex_iterator)、smatch 捕获组及常用 ECMAScript 语法符号。
学完这一章,你能够
- 系统讲解 C++11 正则表达式库 <regex> 的反斜杠转义与原始字符串字面量、核心类与算法(regex_match/search/replace/sregex_iterator)、smatch 捕获组及常用 ECMAScript 语法符号。
正则表达式定位、双反斜杠转义与原始字符串字面量
C++11 标准库头文件 `<regex>` 提供了完整的正则表达式引擎(默认采用 ECMAScript 语法),支持字符串校验、模式提取、多处遍历与按模版替换,广泛应用于表单验证、日志解析与文本清洗。
编写 C++ 正则字面量时最容易踩的坑是**两阶段转义**:C++ 编译器先解析普通字符串字面量中的反斜杠,正则引擎随后再解析生成的字符串。若在普通字符串中写 `"\d+"`,编译器会把 `\d` 当作非法转义序列告警或丢弃反斜杠;因此普通字符串必须写成双反斜杠 `"\\d+"`。为彻底摆脱多层反斜杠困扰,C++11 提供了原始字符串字面量 `R"(\d+)"`,`R"(...)"` 内部不会做 C++ 转义处理,在复杂正则中强烈推荐优先使用。
核心语法元素与主要类/算法接口
正则表达式由四类基础构建块组合而成:字符类(如 `[abc]`、`[A-Z]`、`\d`、`\w`、`\s`);量词(`*` 零或多次、`+` 一或多次、`?` 零或一次、`{n,m}` 区间次数);边界锚点(`^` 开头、`$` 结尾);以及圆括号 `()` 构成的捕获分组与 `|` 分支选择。
`<regex>` 的五大核心组件分工明确:`std::regex` 编译并保存正则自动机;`std::regex_match` 要求**整个目标字符串**完全匹配模式;`std::regex_search` 在字符串任意位置查找首个匹配子串;`std::regex_replace` 将所有(或按标志控制的首个)匹配项替换为指定格式串;`std::sregex_iterator` 则提供标准迭代器接口以顺序遍历全部非重叠匹配项。
典型匹配、搜索、迭代与替换实践
整体校验使用 `std::regex_match`:例如 `std::regex("\\d+")` 匹配 `"12345"` 返回 `true`(但对 `"123ab"` 返回 `false`);`^[a-zA-Z]+, [a-zA-Z]+!$` 整串匹配 `"Hello, World!"`。
部分搜索既可以循环调用 `std::regex_search(text, matches, pattern)` 并令 `text = matches.suffix().str()`(例如从文本中依次提取 `123-456-7890` 与 `987-654-3210`),也可以直接使用 `std::sregex_iterator` 免去反复拷贝后缀字符串。替换操作调用 `std::regex_replace(text, pattern, replacement)`,既可默认全局替换(如把 `"abc123def456"` 中的全部数字替换为 `#` 得 `"abc#def#"`),也可传入 `std::regex_constants::format_first_only` 仅替换首次命中。
下文四张参考表分别汇总了 `<regex>` 常用类型、匹配算法函数、`std::smatch` 结果对象成员以及常见 ECMAScript 正则元字符(注:若用普通 C++ 字符串字面量书写表中含 `\` 的模式如 `\d`,仍须写为 `\\d` 或改用原始字符串 `R"(\d+)"`)。本站已在离线 G++ C++17 容器实测全部类型、算法、捕获组访问、大小写忽略选项与替换标志。
<regex> 常用类与类型对照表
| 名称 | 说明 |
|---|---|
| std::regex | 编译后的 char 正则表达式对象(basic_regex<char> 别名) |
| std::smatch | 保存 std::string 匹配与捕获组结果的 match_results |
| std::cmatch | 保存 C 风格字符串 const char* 匹配结果的 match_results |
| std::sregex_iterator | 遍历 std::string 中所有匹配项的正则迭代器 |
| std::cregex_iterator | 遍历 const char* 中所有匹配项的正则迭代器 |
| std::syntax_option_type | 构造 regex 时的语法与选项位掩码(如 ECMAScript、icase) |
| std::match_flag_type | 控制匹配与替换行为的标志位(如 format_first_only) |
<regex> 常用匹配与替换函数表
| 函数名 | 用途 | 返回值 | 示例 |
|---|---|---|---|
| regex_match(s, re) | 检查整个字符串是否完全符合正则模式 | bool | std::regex_match("123", re) |
| regex_search(s, m, re) | 在字符串中搜索首个匹配子串并将结果写入 m | bool | std::regex_search(s, m, re) |
| regex_replace(s, re, fmt) | 将匹配子串按替换格式 fmt 替换并返回新字符串 | std::string | std::regex_replace(s, re, "#") |
std::smatch 匹配结果成员表
| 成员 | 说明 | 示例 |
|---|---|---|
| m.str() | 返回完整匹配文本(等价于 m[0].str()) | m.str() |
| m[i] | 返回第 i 个子匹配对象(0 为整串匹配,1 起为捕获分组) | m[1].str() |
| m.position() | 返回指定子匹配在原串中的起始偏移位置 | m.position(0) |
| m.size() | 返回匹配组总数(1 + 捕获括号个数) | m.size() |
| m.empty() | 判断本次结果对象是否未包含任何匹配 | m.empty() |
常用正则表达式语法符号表
| 符号 | 含义 | 示例 |
|---|---|---|
| . | 匹配除换行符外的任意单个字符 | a.c 匹配 abc |
| \d | 匹配任意十进制数字 [0-9] | \d+ |
| \w | 匹配字母、数字或下划线 [A-Za-z0-9_] | \w+ |
| \s | 匹配空格、制表符等空白字符 | \s+ |
| ^ | 匹配输入开头位置 | ^abc |
| $ | 匹配输入结尾位置 | xyz$ |
| + | 前导元素出现 1 次或多次 | a+ |
| * | 前导元素出现 0 次或多次 | a* |
| ? | 前导元素出现 0 次或 1 次(也可修饰量词为非贪婪) | a? |
| {n,m} | 前导元素重复 n 到 m 次 | \d{2,4} |
| () | 定义捕获分组以便通过 m[i] 提取 | (ab)+ |
| [] | 字符集合,匹配括号内列举的任意单个字符 | [A-Z] |
| | | 分支选择(逻辑“或”),匹配左侧或右侧模式 | cat|dog |
实测 <regex> 整串匹配与原始字符串、smatch/cmatch 捕获组、sregex_iterator 遍历与替换标志
#include <cstdio>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
int main() {
std::vector<lab::Case> cases;
// Case 1: regex_match with escaped backslash, raw string literal, anchors, quantifiers, alternation
std::regex re_digits("\\d+");
std::regex re_raw(R"(\d{2,4})");
std::regex re_greet("^[a-zA-Z]+, [a-zA-Z]+!$");
std::regex re_alt("cat|dog");
std::regex re_dot("a.c");
std::regex re_word(R"(\w+\s+[A-Z]+)");
std::regex re_quant(R"(a*b?c+(ab)+)");
bool ok1 = std::regex_match("12345", re_digits)
&& !std::regex_match("123ab", re_digits)
&& std::regex_match("2026", re_raw)
&& std::regex_match("Hello, World!", re_greet)
&& std::regex_match("cat", re_alt)
&& std::regex_match("dog", re_alt)
&& std::regex_match("abc", re_dot)
&& std::regex_match("key_1 XYZ", re_word)
&& std::regex_match("ccabab", re_quant);
cases.push_back({
"regex_match_and_raw_string",
lab::jbool(true),
lab::jbool(ok1),
ok1
});
// Case 2: regex_search with smatch, cmatch, cregex_iterator & syntax_option_type::icase
std::string text = "user=Alice id=42";
std::regex re_kv(R"(user=(\w+)\s+id=(\d+))");
std::smatch sm;
bool hit_s = std::regex_search(text, sm, re_kv);
const char* ctext = "CODE:ab12 CODE:cd34";
std::regex re_c("code:([a-z]+)(\\d+)", std::regex_constants::icase);
std::cmatch cm;
bool hit_c = std::regex_search(ctext, cm, re_c);
int c_count = 0;
for (std::cregex_iterator it(ctext, ctext + 19, re_c), end_it; it != end_it; ++it) {
++c_count;
}
std::string act2 = "hit=" + std::to_string(hit_s ? 1 : 0)
+ ";full=" + sm.str()
+ ";g1=" + sm[1].str()
+ ";g2=" + sm[2].str()
+ ";pos=" + std::to_string(sm.position(0))
+ ";sz=" + std::to_string(sm.size())
+ ";empty=" + std::to_string(sm.empty() ? 1 : 0)
+ ";cm=" + (hit_c ? cm[1].str() : "")
+ ";ccnt=" + std::to_string(c_count);
std::string exp2 = "hit=1;full=user=Alice id=42;g1=Alice;g2=42;pos=0;sz=3;empty=0;cm=ab;ccnt=2";
cases.push_back({
"regex_search_and_smatch",
lab::esc(exp2),
lab::esc(act2),
act2 == exp2
});
// Case 3: sregex_iterator and iterative regex_search
std::string phones = "123-456-7890 and 987-654-3210";
std::regex re_phone(R"(\d{3}-\d{3}-\d{4})");
std::string found_phones;
std::string cur = phones;
std::smatch pm;
while (std::regex_search(cur, pm, re_phone)) {
if (!found_phones.empty()) found_phones += ",";
found_phones += pm[0].str();
cur = pm.suffix().str();
}
std::string mixed = "abc123def456";
std::string iter_nums;
for (std::sregex_iterator it(mixed.begin(), mixed.end(), re_digits), end_it; it != end_it; ++it) {
if (!iter_nums.empty()) iter_nums += ",";
iter_nums += it->str();
}
std::string act3 = "phones=" + found_phones + ";nums=" + iter_nums;
std::string exp3 = "phones=123-456-7890,987-654-3210;nums=123,456";
cases.push_back({
"regex_iterator_all_matches",
lab::esc(exp3),
lab::esc(act3),
act3 == exp3
});
// Case 4: regex_replace and match_flag_type::format_first_only
std::string r1 = std::regex_replace(std::string("Hello, World!"), std::regex("World"), "Universe");
std::string r2 = std::regex_replace(mixed, re_digits, "#");
std::string r3 = std::regex_replace(mixed, re_digits, "#", std::regex_constants::format_first_only);
std::string act4 = r1 + "|" + r2 + "|" + r3;
std::string exp4 = "Hello, Universe!|abc#def#|abc#def456";
cases.push_back({
"regex_replace_and_flags",
lab::esc(exp4),
lab::esc(act4),
act4 == exp4
});
lab::emit(cases);
return 0;
}
- 确认双反斜杠与 R"(...)" 整串匹配、smatch/cmatch/icase 捕获组提取、电话号码与数字序列全量迭代,以及全量替换与 format_first_only 单次替换全部准确。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:449a2010481ba72f2e5e248c587f7e3fceebb64afb50e7738aa875a30e64e046
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:b4c0d246840695b69ca7e1797f54186b0e7a486c5399812563fd0a7c33d1425e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`std::regex_match` 与 `std::regex_search` 在匹配语义上有何本质区别?
展开参考解答
`std::regex_match` 要求整个输入字符串从头到尾完全匹配正则表达式才会返回 `true`;`std::regex_search` 只要字符串内部存在任意满足模式的子串就会返回 `true`。