std::regex
是 C++11 引入的 正则表达式库,用于 字符串匹配、搜索和替换。
头文件:#include
命名空间:std
支持的匹配模式:ECMAScript(默认)、POSIX 规则等。
组件 | 作用 | 示例 |
---|---|---|
std::regex |
正则表达式对象 | std::regex pattern("\\d+"); |
std::regex_match |
完全匹配字符串 | std::regex_match("123", pattern); |
std::regex_search |
搜索子串匹配 | std::regex_search("abc123", pattern); |
std::regex_replace |
替换匹配部分 | std::regex_replace("abc123", pattern, "***"); |
std::smatch |
存储匹配结果(字符串版) | std::smatch match; |
std::cmatch |
存储匹配结果(C 字符串版) | std::cmatch match; |
(1)检查字符串是否完全匹配
#include
#include
int main() {
std::string str = "123";
std::regex pattern("\\d+"); // 匹配数字
if (std::regex_match(str, pattern)) {
std::cout << "完全匹配!" << std::endl;
} else {
std::cout << "匹配失败!" << std::endl;
}
}
(2)搜索字符串中是否包含匹配项
#include
#include
int main() {
std::string str = "abc123xyz";
std::regex pattern("\\d+"); // 查找数字
std::smatch match;
// std::regex_search() 适用于 查找子字符串是否匹配 的情况
if (std::regex_search(str, match, pattern)) {
std::cout << "找到匹配: " << match[0] << std::endl;
}
}
(3)字符串替换
#include
#include
int main() {
std::string str = "hello 123 world";
std::regex pattern("\\d+"); // 目标:匹配数字
// std::regex_replace() 适用于 将匹配项替换为新内容
std::string replaced = std::regex_replace(str, pattern, "***");
std::cout << "替换后:" << replaced << std::endl;
}
(4)提取多个匹配项
#include
#include
int main() {
std::string str = "email: [email protected], contact: [email protected]";
std::regex pattern(R"([\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,})"); // 匹配邮箱
std::smatch match;
while (std::regex_search(str, match, pattern)) {
std::cout << "找到邮箱: " << match[0] << std::endl;
str = match.suffix(); // 继续查找
}
}
(1)常见正则语法
表达式 | 作用 | 示例匹配 |
---|---|---|
\d |
数字 | "123" |
\w |
字母、数字、下划线 | "abc_123" |
. |
任意字符(除换行) | "a" "!" |
\s |
空格 | " " |
^ |
字符串开头 | ^abc 匹配 "abc123" 但不匹配 "1abc" |
$ |
字符串结尾 | abc$ 匹配 "123abc" |
+ |
至少一个 | \d+ 匹配 "123" "4567" |
* |
0 个或多个 | a* 匹配 "" "a" "aaaa" |
? |
0 或 1 个 | colou?r 匹配 "color" 和 "colour" |
{n,m} |
重复 n 到 m 次 | \d{2,4} 匹配 "12" "1234" |
() |
分组 | (\d+)-(\d+) |
` | ` | 或 |
(2)特殊匹配
语法 | 作用 |
---|---|
(?:...) |
非捕获组 |
(?=...) |
正向预查 |
(?!...) |
负向预查 |
1. std::regex 在 GCC 4.8.5 及以下版本崩溃
GCC 4.8.5 的 std::regex
不稳定,容易崩溃。
解决方案:
升级 GCC 4.9+
使用 boost::regex
代替
使用 pcre
代替
2. std::regex 解析长字符串性能差
解决方案:
std::sregex_iterator
遍历字符串。boost::regex
或 pcre
,它们更快。3. std::regex_replace()处理大文本效率低
解决方案:
std::ostringstream
手动拼接字符串,减少替换操作。方法 | 适用场景 | 速度 | 兼容性 |
---|---|---|---|
std::regex |
C++11 及以上,简单匹配 | 较慢 | 仅 C++11+ |
boost::regex |
C++98 兼容,功能强大 | 中等 | 兼容 C++98 |
PCRE |
高效匹配大文本 | 最快 | 需要安装 |
手写字符串查找 |
仅匹配简单内容 | 最快 | 兼容所有 C++ |
功能 | 使用方法 |
---|---|
完全匹配 | std::regex_match(str, pattern); |
搜索字符串 | std::regex_search(str, match, pattern); |
替换字符串 | std::regex_replace(str, pattern, "new"); |
遍历所有匹配 | std::sregex_iterator |
推荐
std::regex
。boost::regex
。PCRE
。