C++中使用std::regex需包含头文件,主要类型有std::regex、std::smatch等;std::regex_match要求整个字符串完全匹配模式,而std::regex_search用于查找部分匹配子串。

在C++中使用正则表达式,主要依赖于标准库中的 std::regex。该功能从 C++11 开始引入,提供了强大的文本匹配、搜索和替换能力。本文将详细介绍如何使用 C++ 的 regex 库进行常见操作,包括模式匹配、查找子串、提取内容以及字符串替换。
一、包含头文件与基本类型
要使用正则功能,需包含头文件:#include
- std::regex:编译后的正则表达式对象
- std::smatch:用于匹配 std::string 的结果容器
- std::regex_match:判断整个字符串是否匹配
- std::regex_search:在字符串中搜索匹配的子串
- std::regex_replace:替换匹配的部分
二、完整匹配 vs 部分匹配
区别在于是否要求整个字符串符合模式。std::regex_match 要求整个字符串完全匹配模式:
#include若 text 为 "abc123",则不会匹配,因为不是全部由数字组成。#include #include int main() { std::string text = "12345"; std::regex pattern(R"(\d+)"); // 匹配一个或多个数字 if (std::regex_match(text, pattern)) { std::cout << "完全匹配\n"; } }
std::regex_search 只要找到一处匹配即可:
立即学习“C++免费学习笔记(深入)”;
std::string text = "ID: 12345, name: Tom";
std::regex pattern(R"(\d+)");
std::smatch match;
if (std::regex_search(text, match, pattern)) {
std::cout << "找到数字: " << match.str() << "\n"; // 输出 12345
}
三、提取匹配的子组
用括号 () 定义捕获组,通过 smatch 获取各部分。例如,解析日期格式 YYYY-MM-DD:
std::string date = "2023-10-05";
std::regex pattern(R"((\d{4})-(\d{2})-(\d{2}))");
std::smatch match;
if (std::regex_match(date, match, pattern)) {
std::cout << "年: " << match[1] << "\n"; // 2023
std::cout << "月: " << match[2] << "\n"; // 10
std::cout << "日: " << match[3] << "\n"; // 05
}
match[0] 是完整匹配,match[1], match[2]... 对应括号内的子表达式。
四、字符串替换(regex_replace)
std::regex_replace 可以替换所有匹配项。示例:将多个空格替换为单个空格:
std::string text = "a b c"; std::regex space_pattern(R"( +)"); std::string result = std::regex_replace(text, space_pattern, " "); // result 变为 "a b c"也可用于格式化,比如交换名字顺序:
std::string name = "Doe, John"; std::regex name_pattern(R"((\w+), (\w+))"); std::string formatted = std::regex_replace(name, name_pattern, "$2 $1"); // 结果为 "John Doe"$1、$2 表示第一个和第二个捕获组。
五、常见正则语法示例
-
\d:数字,等价于 [0-9] -
\w:字母、数字、下划线 -
\s:空白字符(空格、制表符等) -
*:前一项出现 0 次或多次 -
+:前一项出现 1 次或多次 -
?:前一项出现 0 或 1 次 -
{n,m}:前一项出现 n 到 m 次 -
^:行首(在多行模式下有效) -
$:行尾
基本上就这些。掌握 regex_match、regex_search 和 regex_replace 三大函数,配合 smatch 提取信息,就能应对大多数文本处理需求。注意性能:频繁使用时建议复用 std::regex 对象,不要每次都构造。不复杂但容易忽略。










