C++中使用头文件支持正则表达式,通过std::regex、std::smatch、std::regex_match、std::regex_search和std::regex_replace实现匹配、搜索与替换;regex_match要求全字符串匹配,regex_search只需部分匹配,捕获组可提取子表达式,适用于验证、提取和替换场景。

在C++中使用正则表达式匹配字符串,主要依赖于头文件提供的功能。从C++11开始,标准库引入了对正则表达式的支持,可以通过std::regex及相关函数实现模式匹配、搜索、替换等操作。
包含头文件并了解核心类
要使用正则表达式,必须包含头文件。常用的核心组件包括:
- std::regex:编译后的正则表达式对象
- std::smatch:用于保存字符串匹配结果(针对std::string)
- std::regex_match:判断整个字符串是否匹配正则表达式
- std::regex_search:在字符串中查找符合正则的部分
- std::regex_replace:替换匹配到的内容
#include#include #include int main() { std::string text = "Hello, my email is example@email.com"; std::regex pattern(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)"); // 检查是否存在邮箱 if (std::regex_search(text, pattern)) { std::cout << "Found an email address!" << std::endl; } // 提取匹配内容 std::smatch match; if (std::regex_search(text, match, pattern)) { std::cout << "Email found: " << match[0] << std::endl; } return 0; }
regex_match 与 regex_search 的区别
这两个函数用途不同,需根据场景选择:
- std::regex_match 要求整个字符串完全符合正则表达式。例如验证输入格式(如电话号码、身份证)时使用。
- std::regex_search 只要字符串中有部分匹配即可,适合从文本中提取信息。
std::string str = "123abc";
std::regex r("\\d+"); // 匹配一个或多个数字
// regex_match:整个字符串必须是数字 → 不匹配
if (!std::regex_match(str, r)) {
std::cout << "regex_match failed" << std::endl;
}
// regex_search:只要有一段是数字 → 匹配成功
if (std::regex_search(str, r)) {
std::cout << "regex_search succeeded" << std::endl;
}
提取分组信息(捕获括号)
正则中的圆括号()可用于定义捕获组,方便提取特定部分。
立即学习“C++免费学习笔记(深入)”;
std::string log = "2025-04-05 14:30:22 ERROR Network failure";
std::regex log_pattern(R"((\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+) (.+))");
std::smatch pieces;
if (std::regex_match(log, pieces, log_pattern)) {
std::cout << "Date: " << pieces[1] << "\n";
std::cout << "Time: " << pieces[2] << "\n";
std::cout << "Level: " << pieces[3] << "\n";
std::cout << "Message: " << pieces[4] << std::endl;
}
pieces[0] 是完整匹配,pieces[1], pieces[2]... 对应各个括号内的子表达式。
常见应用场景与技巧
-
验证输入:比如检查手机号、邮箱、日期格式是否合法,用
regex_match。 -
数据提取:从日志、HTML片段中抓取所需字段,用
regex_search配合smatch。 -
批量替换:
regex_replace可将匹配内容替换成指定字符串。
std::string sentence = "User called John has logged in.";
std::regex name_pattern("John");
std::string new_sentence = std::regex_replace(sentence, name_pattern, "Alice");
// 结果:"User called Alice has logged in."
基本上就这些。熟练掌握regex_match、regex_search和捕获组的使用,就能应对大多数文本处理任务。注意正则表达式语法错误会在运行时抛出异常,建议加try-catch保护。











