C++中使用正则需包含头文件,支持regex_match(完全匹配)、regex_search(部分查找)和regex_replace(替换),结合smatch提取分组信息,可实现字符串验证、查找、替换等操作。

在C++中使用正则表达式,主要依赖于标准库中的
包含头文件和命名空间
使用正则表达式前,需要引入头文件并使用 std 命名空间:
#include iostream>#include
#include
using namespace std;
基本匹配:std::regex_match
regex_match 用于判断整个字符串是否完全匹配某个正则表达式。
示例:验证一个字符串是否为纯数字
立即学习“C++免费学习笔记(深入)”;
string str = "12345";regex pattern(R"(\d+)"); // 匹配一个或多个数字
if (regex_match(str, pattern)) {
cout }
注意:R"(...)" 是原始字符串字面量,避免转义字符的麻烦。
部分查找:std::regex_search
regex_search 用于在字符串中查找是否存在符合正则的部分。
示例:查找字符串中是否有邮箱格式
string text = "联系我:test@example.com";regex email_pattern(R"(\w+@\w+\.\w+)");
smatch match; // 用于保存匹配结果
if (regex_search(text, match, email_pattern)) {
cout }
smatch 是 std::match_results<:const_iterator> 的别名,match[0] 表示整个匹配内容。
提取分组信息
使用括号 () 可以定义捕获组,提取特定部分。
示例:提取日期中的年月日
string date_str = "2024-04-05";regex date_pattern(R"((\d{4})-(\d{2})-(\d{2}))");
smatch result;
if (regex_match(date_str, result, date_pattern)) {
cout }
字符串替换:std::regex_replace
可以用正则表达式替换匹配到的内容。
示例:将所有连续空格替换为单个空格
string input = "a b c";regex space_pattern(R"(\s+)");
string output = regex_replace(input, space_pattern, " ");
cout
常见正则表达式示例
- 手机号(中国大陆): R"(^1[3-9]\d{9}$)"
- 邮箱: R"(\w+@\w+\.\w+)"(简化版)
- IP 地址(简化): R"(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)"
- URL: R"(https?://\S+)"
基本上就这些。掌握 regex_match、regex_search 和 regex_replace 三个核心函数,配合 smatch 提取结果,就能满足大多数文本处理需求。注意正则表达式写法要正确,复杂模式建议先测试验证。











