std::regex
是 C++11 引入的 正則表達式庫,用于 字符串匹配、搜索和替換。
🔹 頭文件:#include <regex>
🔹 命名空間: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 <iostream>
#include <regex>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 <iostream>
#include <regex>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 <iostream>
#include <regex>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 <iostream>
#include <regex>int main() {std::string str = "email: test@example.com, contact: user@mail.com";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
。 - 老版本 C++(C++98/C++03):使用
boost::regex
。 - 高性能需求:使用
PCRE
。