C++中使用正则需包含头文件,支持匹配、搜索、替换和分组提取。1. regex_match判断完全匹配;2. regex_search查找子串;3. smatch保存结果并提取分组;4. regex_replace替换文本;5. 复用regex对象提升性能,注意异常处理。

在C++中使用正则表达式需要借助标准库中的
包含头文件与命名空间
使用正则表达式前,先包含头文件:
#include#include
#include iostream>
通常使用 std 命名空间简化代码:
using namespace std;基本匹配:std::regex_match
regex_match 用于判断整个字符串是否完全匹配某个正则表达式。
立即学习“C++免费学习笔记(深入)”;
string text = "hello123";regex pattern(R"([a-z]+[0-9]+)"); // 匹配字母后跟数字
if (regex_match(text, pattern)) {
cout }
R"(...)" 是原始字符串字面量,避免转义字符的麻烦。
部分搜索:std::regex_search
regex_search 用于在字符串中查找符合正则的部分内容。
string text = "Contact us at support@example.com or admin@test.org";regex email_pattern(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)");
smatch matches; // 用于保存匹配结果
while (regex_search(text, matches, email_pattern)) {
cout 邮箱: " text = matches.suffix(); // 更新剩余字符串继续搜索
}
smatch 是 std::match_results<:const_iterator> 的别名,matches[0] 表示完整匹配,括号捕获的内容可用 matches[1], matches[2] 等访问。
提取分组信息
用括号定义捕获组,可以提取特定部分。
string log = "2024-05-10 ERROR: Failed to connect";regex log_pattern(R"((\d{4}-\d{2}-\d{2})\s+(\w+):\s+(.*))");
smatch result;
if (regex_search(log, result, log_pattern)) {
cout cout cout }
字符串替换:std::regex_replace
将匹配的部分替换成指定内容。
string input = "Call me at 123-456-7890 or 987-654-3210";regex phone_pattern(R"(\d{3}-\d{3}-\d{4})");
string output = regex_replace(input, phone_pattern, "[PHONE]");
cout
regex_replace 不修改原字符串,而是返回新字符串。
常见正则语法说明
C++ regex 默认使用 ECMAScript 风格语法,常用规则包括:
- \d 数字 [0-9]
- \w 单词字符 [a-zA-Z0-9_]
- \s 空白字符
- * 重复0次或多次
- + 重复1次或多次
- ? 0次或1次
- {n,m} 重复n到m次
- ^ 行首
- $ 行尾
- [...] 字符集合
- (...) 捕获组
性能提示与注意事项
regex 对象构造较耗时,建议复用而不是频繁创建。
static const regex number_pattern(R"(\d+)"); // 使用 static 避免重复构造注意异常处理:如果正则表达式格式错误,构造 regex 对象会抛出 std::regex_error。
try {regex bad_regex("*invalid*");
} catch (const regex_error& e) {
cout } 基本上就这些。掌握 match、search、replace 和分组提取,就能应对大多数文本处理需求。正则功能强大,但复杂模式可能影响可读性,建议配合注释使用。











