跳到主要内容
版本:1.0

regex

std::regex 是 C++11 引入的正则表达式库,用于字符串匹配、搜索和替换。

它把常见的文本处理能力标准化到了 STL 体系中,适合做格式校验、日志提取、批量替换等任务。

头文件与基本用法

使用正则时通常包含:

#include <regex>

最常见的三个函数:

  1. std::regex_match:要求整段文本完全匹配。
  2. std::regex_search:查找文本里任意一个匹配片段。
  3. std::regex_replace:替换匹配到的内容。

示例:

#include <iostream>
#include <regex>
#include <string>

int main() {
std::string s = "order-42";
std::regex rule("order-[0-9]+");

if (std::regex_match(s, rule)) {
std::cout << "match\n";
}
}

交互演示(MDX + React)

下面面板可实时输入 pattern、flags、文本与替换串,查看 test、search、match-all、replace 的结果变化:

regex 交互演示

MDX + React

regex_match / test: true

regex_search 首次位置: 6

regex_iterator 全部匹配: [42, 7]

regex_replace 结果: order-# and room-#

常见接口

接口作用
std::regex编译正则表达式
std::smatch基于 std::string 的匹配结果容器
std::regex_match全匹配
std::regex_search子串搜索
std::regex_replace替换
std::sregex_iterator遍历全部匹配

子匹配提取

#include <iostream>
#include <regex>
#include <string>

int main() {
std::string text = "name=tom age=18";
std::regex rule("name=([a-z]+) age=([0-9]+)");
std::smatch m;

if (std::regex_search(text, m, rule)) {
std::cout << m[1] << "\n"; // tom
std::cout << m[2] << "\n"; // 18
}
}

使用注意

  1. regex_match 是全匹配,很多人本来想做子串匹配却误用了它。
  2. 正则表达式写错会抛出 std::regex_error,建议加异常处理。
  3. 复杂正则在热点路径上可能较慢,必要时要评估性能。
  4. 做简单前后缀判断时,普通字符串函数通常更轻量。

小结

std::regex 适合中等复杂度的文本规则处理。掌握 match、search、replace 和分组提取后,日常字符串清洗与校验基本都能覆盖。