**1. 基本正则表达式语法**
正则表达式使用特定字符组合表示字符串模式,常见元字符包括:
- `.`:匹配任意单个字符(除换行符)
- `*`:匹配前面的字符/表达式 0 次或多次
- `+`:匹配前面的字符/表达式 1 次或多次
- `?`:匹配前面的字符/表达式 0 次或 1 次
- `[]`:匹配方括号内的任意一个字符(如 `[abc]` 匹配 `a`、`b` 或 `c`)
- `^`:在 `[]` 内表示取反(如 `[^0-9]` 匹配非数字字符)
- `$`:匹配字符串的结尾
- `\d`:匹配数字(等价于 `[0-9]`)
- `\s`:匹配空白字符(空格、制表符等)
- `\w`:匹配单词字符(字母、数字、下划线)
**2. C++ 正则表达式库的核心组件**
C++ 的 `<regex>` 库提供了以下关键类和函数:
**(1) `std::regex`**
用于创建和存储正则表达式模式。
cpp
#include <regex>
std::regex pattern("\\d+"); // 匹配一个或多个数字
**(2) 匹配函数**
- `std::regex_match`:判断整个字符串是否匹配模式。
- `std::regex_search`:在字符串中查找第一个匹配的子串。
- `std::regex_replace`:替换匹配的子串。
**(3) 迭代器**
- `std::sregex_iterator`:用于遍历所有匹配结果(字符串类型)。
- `std::smatch`:存储单次匹配的结果(如捕获组)。
**3. 示例代码**
**(1) 基本匹配**
cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "Hello, 2023!";
std::regex pattern("\\d+"); // 匹配数字
// 使用 regex_search 查找第一个匹配
if (std::regex_search(text, pattern)) {
std::cout << "找到数字!" << std::endl;
}
// 使用 regex_match 判断整个字符串是否匹配
if (std::regex_match(text, std::regex("Hello.*"))) {
std::cout << "字符串以 'Hello' 开头!" << std::endl;
}
return 0;
}
**(2) 捕获组**
使用括号 `()` 创建捕获组,提取匹配的部分:
cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string email = "user@example.com";
std::regex pattern("(\\w+)@(\\w+\\.\\w+)"); // 两个捕获组:用户名和域名
std::smatch match;
if (std::regex_search(email, match, pattern)) {
std::cout << "用户名: " << match[1] << std::endl; // 第一个捕获组
std::cout << "域名: " << match[2] << std::endl; // 第二个捕获组
}
return 0;
}
**(3) 替换匹配结果**
cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "Hello, 2023! Next year is 2024.";
std::regex pattern("\\d{4}"); // 匹配四位数字
// 将所有年份替换为 "XXXX"
std::string result = std::regex_replace(text, pattern, "XXXX");
std::cout << "替换后: " << result << std::endl;
return 0;
}
**(4) 遍历所有匹配结果**
cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "苹果 10元,香蕉 5元,橘子 8元";
std::regex pattern("(\\D+)(\\d+)元"); // 匹配 "水果名称 + 价格"
// 使用迭代器遍历所有匹配
std::sregex_iterator current(text.begin(), text.end(), pattern);
std::sregex_iterator end;
while (current != end) {
std::smatch match = *current;
std::cout << "水果: " << match[1] << ",价格: " << match[2] << "元" << std::endl;
++current;
}
return 0;
}
**4. 注意事项**
1. **转义字符**:在 C++ 字符串中,反斜杠 `\` 需要转义为 `\\`(如 `\\d` 表示数字)。
2. **性能**:复杂正则表达式可能影响性能,建议编译后复用 `std::regex` 对象。
3. **异常处理**:无效的正则表达式模式会抛出 `std::regex_error` 异常,需捕获处理。
cpp
try {
std::regex invalid_pattern("[a-z"); // 缺少右括号,会抛出异常
} catch (const std::regex_error& e) {
std::cerr << "正则表达式错误: " << e.what() << std::endl;
}
**5. 常见应用场景**
- **验证输入**(如邮箱、手机号、密码强度)。
- **提取数据**(如从 HTML 中提取链接)。
- **格式化文本**(如替换敏感词、统一日期格式)。
通过灵活组合正则表达式语法和 C++ 库函数,可以高效处理各种文本处理任务。