std::regex 是 C++11 引入的标准正则库,用法清晰但需注意匹配模式、异常处理和性能细节。它不支持所有 Perl 风格语法(如 \K、递归),也不默认启用 Unicode 模式,实际使用时建议从基础匹配、搜索、替换三类操作入手。
用 std::regex_match 判断整个字符串是否完全匹配正则表达式:
std::string text = "2025-05-20";
std::regex pattern(R"(^\d{4}-\d{2}-\d{2}$)");
if (std::regex_match(text, pattern)) {
std::cout << "格式正确\n";
}
用 std::regex_search 查找第一个匹配子串,配合 std::smatch 获取捕获组:
rch 实现多次查找(传入上次结束位置);std::string email = "contact: user@example.com";
std::regex mail_pat(R"((\w+)@(\w+\.\w+))");
std::smatch result;
if (std::regex_search(email, result, mail_pat)) {
std::cout << "用户名:" << result[1].str() << "\n"; // user
}
用 std::regex_replace 批量替换匹配内容,支持 $1、$2 引用捕获组:
std::string date = "2025-05-20";
std::regex ymd_pat(R"((\d{4})-(\d{2})-(\d{2}))");
std::string new_date = std::regex_replace(date, ymd_pat, "$3/$2/$1");
// → "20/05/2025"
std::regex 在不同编译器实现差异较大(尤其 GCC libstdc++ 早期版本性能差、功能弱),使用前确认: