答案:C++11起通过头文件支持正则表达式,需包含头文件并使用std命名空间;regex_match用于全字符串匹配,如验证纯数字。

在C++中使用正则表达式需要借助标准库中的头文件。从C++11开始,正则表达式被正式纳入标准,提供了强大的文本匹配、查找和替换功能。
包含头文件并引入命名空间
要使用正则表达式,首先需要包含头文件,并建议使用std命名空间以简化代码:
#include#include #include using namespace std;
基本匹配:regex_match
regex_match用于判断整个字符串是否完全匹配某个正则表达式。
示例:验证一个字符串是否为纯数字
立即学习“C++免费学习笔记(深入)”;
string text = "12345";
regex pattern(R"(\d+)");
if (regex_match(text, pattern)) {
cout << "完全匹配" << endl;
}
注意:这里使用了原始字符串字面量R"()"避免双反斜杠问题,例如"\\d+"等价于R"(\d+)"。
查找匹配:regex_search
regex_search用于在字符串中搜索符合正则表达式的子串。
示例:查找字符串中第一个数字序列
string text = "abc123def456"; regex pattern(R"(\d+)"); smatch match;if (regex_search(text, match, pattern)) { cout << "找到匹配: " << match.str() << endl; // 输出 123 }
smatch是std::match_results<:const_iterator>的别名,用于保存匹配结果。
多次查找所有匹配项
通过循环调用regex_search,可以找到所有匹配的子串。
1 系统使用三层构架2 数据库访问使用sqlHelper3 编辑器使用FreeTextBox4 布局采用Div+Css5 正则表达式实现数据验证6 动态构建sql查询语句
string text = "abc123def456ghi789"; regex pattern(R"(\d+)"); sregex_iterator iter(text.begin(), text.end(), pattern); sregex_iterator end;for (; iter != end; ++iter) { cout << "匹配到: " << iter->str() << endl; } // 输出:123, 456, 789
sregex_iterator是专门用于遍历所有匹配结果的迭代器。
字符串替换:regex_replace
regex_replace可以将匹配的部分替换成指定内容。
示例:将所有数字替换为"*"
string text = "abc123def456"; regex pattern(R"(\d+)"); string result = regex_replace(text, pattern, "*"); cout << result << endl; // 输出 abc*def*
该函数不会修改原字符串,而是返回一个新的字符串。
捕获分组(Group Capture)
正则表达式支持用括号()进行分组,提取特定部分。
示例:提取日期中的年月日
string date = "2023-10-05";
regex pattern(R"((\d{4})-(\d{2})-(\d{2}))");
smatch match;
if (regex_search(date, match, pattern)) {
cout << "年: " << match[1] << endl; // 2023
cout << "月: " << match[2] << endl; // 10
cout << "日: " << match[3] << endl; // 05
}
match[0]表示完整匹配,match[1]、match[2]等对应各个捕获组。
常见正则表达式示例
- 邮箱验证:
R"(^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)" - 手机号(中国大陆):
R"(^1[3-9]\d{9}$)" - IP地址(简单版):
R"((\d{1,3}\.){3}\d{1,3})" - 去除空白行:
R"(^\s*$)"
基本上就这些。掌握regex_match、regex_search、regex_replace和捕获组就能应对大多数场景。注意性能问题,频繁使用的正则表达式应定义为全局或静态对象以避免重复构造。









