C++中使用头文件实现正则匹配,通过std::regex_match判断字符串是否完全符合模式,需包含和,支持搜索、替换等操作。

在C++中使用正则表达式进行字符串匹配,主要依赖于标准库中的
包含头文件并引入命名空间
要使用正则功能,首先需要包含头文件:
#include
通常也会用到 #include
为方便书写,可以使用:
using namespace std;
立即学习“C++免费学习笔记(深入)”;
基本的字符串匹配:std::regex_match
std::regex_match 用于判断整个字符串是否完全匹配某个正则模式。
示例:
string text = "hello123";
regex pattern(R"([a-z]+[0-9]+)"); // 匹配字母后跟数字
if (regex_match(text, pattern)) {
cout << "完全匹配!" << endl;
}
注意:regex_match 要求整个字符串符合模式,部分匹配会返回 false。
查找子串匹配:std::regex_search
如果只想判断字符串中是否存在符合模式的子串,应使用 std::regex_search。
示例:查找邮箱地址
string content = "联系我 at example@email.com 或 support@site.org";
regex email_pattern(R"(\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b)");
smatch matches;
while (regex_search(content, matches, email_pattern)) {
cout << "找到邮箱: " << matches[0] << endl;
content = matches.suffix(); // 更新剩余字符串继续搜索
}
这里 smatch 用于保存匹配结果,matches[0] 是完整匹配,suffix() 返回未匹配的后缀部分。
提取分组信息
正则表达式支持用括号 () 定义捕获组,可用来提取特定内容。
例如提取日期中的年月日:
string date_str = "今天是2024-04-05";
regex date_regex(R"((\d{4})-(\d{2})-(\d{2}))");
smatch result;
if (regex_search(date_str, result, date_regex)) {
cout << "年: " << result[1] << endl; // 第一组
cout << "月: " << result[2] << endl; // 第二组
cout << "日: " << result[3] << endl; // 第三组
}
字符串替换:std::regex_replace
可以用 regex_replace 将匹配的内容替换成指定字符串。
示例:将所有数字替换为 *:
string input = "abc123def456"; regex digits(R"(\d+)"); string output = regex_replace(input, digits, "*"); cout << output << endl; // 输出 abc*def*
也可以使用格式化替换,比如交换名字顺序:
string name = "Zhang, Xiaoming"; regex name_format(R"((\w+),\s*(\w+))"); string formatted = regex_replace(name, name_format, "$2 $1"); cout << formatted << endl; // 输出 Xiaoming Zhang
常见正则模式写法
一些常用的正则表达式模式:
- [a-zA-Z]+:匹配一个或多个字母
- \d+:匹配一个或多个数字
- \s+:匹配空白字符(空格、制表符等)
- .*?:非贪婪匹配任意字符
- \bword\b:匹配完整单词
建议使用原始字符串字面量 R"(...)” 避免转义问题,如 R"(\d{3}-\d{3})" 比 "\\\\d{3}-\\\\d{3}" 更清晰。
基本上就这些常用操作。掌握 regex_match、regex_search 和 regex_replace 这三个核心函数,配合合理的模式设计,就能高效处理大多数文本匹配任务。











