c++如何用std::regex处理正则表达式 c++正则库入门【实例】

c++kquote>std::regex是C++11标准正则库,支持匹配、搜索、替换三类操作;regex_match要求全串匹配,需显式指定字符类型并捕获regex_error异常。

std::regex 是 C++11 引入的标准正则库,用法清晰但需注意匹配模式、异常处理和性能细节。它不支持所有 Perl 风格语法(如 \K、递归),也不默认启用 Unicode 模式,实际使用时建议从基础匹配、搜索、替换三类操作入手。

基础匹配:判断字符串是否符合模式

std::regex_match 判断整个字符串是否完全匹配正则表达式:

  • 必须全串匹配,不能是子串;
  • 推荐显式指定字符类型(如 std::regex_pattern)避免模板推导问题;
  • 若正则语法错误,会抛出 std::regex_error 异常,建议 try-catch。
示例:
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 获取捕获组:

  • smatch 类似 vector,下标 0 是整个匹配,1 开始是括号内分组;
  • 可循环调用 regex_search 实现多次查找(传入上次结束位置);
  • 注意:search 不要求整串匹配,适合日志解析、URL 提取等场景。
示例(提取邮箱用户名):
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::regex_replace 的重载版本配合 std::regex_constants::format_first_only。
示例(日期格式转换):
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++ 早期版本性能差、功能弱),使用前确认:

  • std::regex_constants::ECMAScript 显式指定语法标准(默认即此);
  • 避免在循环中反复构造 regex 对象——提前定义为 static 或 const;
  • 中文或 UTF-8 字符需自行按字节处理,std::regex 不识别 Unicode 码点(不支持 \p{L} 等);
  • 复杂需求(如回溯控制、命名捕获)建议换用 Boost.Regex 或 PCRE2 绑定。