C++中使用正则需包含头文件,支持匹配、查找、替换等操作。1. regex_match判断全字符串匹配;2. regex_search查找首个子串;3. 捕获组用()提取分组信息;4. regex_replace实现字符串替换;5. sregex_iterator遍历所有匹配结果。建议复用regex对象提升性能。

在C++中使用正则表达式需要借助标准库中的
包含头文件并引入命名空间
使用正则前,先包含头文件:
#include iostream>#include
#include
using namespace std;
1. 简单匹配:判断字符串是否符合模式
使用 std::regex_match 判断整个字符串是否匹配某个正则表达式。
string text = "12345";regex pattern(R"(\d+)"); // 匹配一个或多个数字
if (regex_match(text, pattern)) {
cout }
注意:regex_match 要求整个字符串都符合模式,部分匹配会返回 false。
立即学习“C++免费学习笔记(深入)”;
2. 查找子串:提取符合模式的部分
使用 std::regex_search 在字符串中搜索第一个匹配的子串。
string text = "我的电话是 13812345678";regex pattern(R"(\d{11})"); // 匹配11位数字
smatch result; // 用于保存匹配结果
if (regex_search(text, result, pattern)) {
cout }
smatch 是 std::match_results 的别名,result[0] 表示完整匹配内容。
3. 提取分组信息
正则中用括号 () 定义捕获组,可在结果中单独提取。
string text = "姓名:张三,年龄:25";regex pattern(R"(姓名:(\w+),年龄:(\d+))");
smatch result;
if (regex_search(text, result, pattern)) {
cout cout }
4. 替换字符串
使用 std::regex_replace 将匹配内容替换成指定字符串。
string text = "用户ID:abc123,密码:******";regex pattern(R"(\b[a-zA-Z]+\d+\b)"); // 匹配字母+数字的组合
string output = regex_replace(text, pattern, "****");
cout
5. 遍历所有匹配结果
使用迭代器遍历字符串中所有匹配项。
string text = "订单编号:A123, B456, C789";regex pattern(R"([A-Z]\d{3})");
sregex_iterator iter(text.begin(), text.end(), pattern);
sregex_iterator end;
while (iter != end) {
cout str() ++iter;
}
基本上就这些。C++ 正则功能强大但语法略复杂,建议从小例子开始练习,注意转义字符的写法(可用原始字符串 R"(...)" 避免反斜杠问题)。实际使用时也要考虑性能,频繁匹配可将 regex 对象复用,避免重复构造。










