C++中使用库进行正则匹配,需包含头文件并启用C++11;regex_match判断全匹配,regex_search查找子串,regex_replace实现替换,smatch提取分组,支持模式搜索与文本处理。

在C++中使用正则表达式匹配字符串,主要依赖于标准库中的
包含头文件并使用命名空间
要使用正则功能,首先需要引入头文件:
#include#include
#include iostream>
通常还会使用 std 命名空间以简化代码:
using namespace std;基本匹配:std::regex_match
std::regex_match 用于判断整个字符串是否完全匹配某个正则表达式。
立即学习“C++免费学习笔记(深入)”;
string text = "hello123";regex pattern(R"([a-z]+[0-9]+)"); // 匹配字母后跟数字
if (regex_match(text, pattern)) {
cout }
注意:regex_match 要求整个字符串符合模式,部分匹配会返回 false。
查找匹配:std::regex_search
std::regex_search 用于在字符串中查找是否存在符合正则的部分。
regex pattern("[0-9]+");
smatch match; // 用于保存匹配结果
if (regex_search(text, match, pattern)) {
cout }
smatch 是 std::match_results<:const_iterator> 的别名,match[0] 表示完整匹配内容。
提取分组信息
正则表达式支持用括号 () 定义捕获组,可用于提取特定部分。
string text = "name: Alice, age: 25";regex pattern(R"(name:\s*(\w+),\s*age:\s*(\d+))");
smatch match;
if (regex_search(text, match, pattern)) {
cout }
match[1] 对应第一个括号内的内容,match[2] 对应第二个。
替换操作:std::regex_replace
可以用 regex_replace 将匹配内容替换成指定字符串。
string text = "phone: 123-456-7890";regex pattern(R"(\d{3}-\d{3}-\d{4})");
string result = regex_replace(text, pattern, "XXX-XXX-XXXX");
cout
基本上就这些常用方法。掌握 regex_match、regex_search 和 regex_replace,配合 smatch 提取子串,就能应对大多数字符串匹配需求。注意编译时需启用 C++11 或更高标准。











