<regex> 提供 ECMAScript 風格正則,語法與 JavaScript 相近。
#include <regex>
#include <string>
#include <iostream>
int main() {
std::string text = "Email: user@example.com, Phone: 0912-345678";
std::regex email(R"(\b[\w.+-]+@[\w-]+\.[\w.-]+\b)");
std::regex phone(R"(\b09\d{2}[- ]?\d{3}[- ]?\d{3}\b)");
// 搜尋第一個匹配
std::smatch m;
if (std::regex_search(text, m, email)) {
std::cout << "Email: " << m[0] << '\n';
}
// 遍歷所有匹配
for (std::sregex_iterator it(text.begin(), text.end(), phone), end; it != end; ++it) {
std::cout << "Phone: " << it->str() << '\n';
}
// 替換
std::string masked = std::regex_replace(text, email, "[EMAIL]");
std::cout << masked << '\n';
}
| 類別/函數 | 用途 |
|---|---|
| `std::regex` | 編譯正則模式物件(昂貴操作,建議重用) |
| `std::smatch` / `std::cmatch` | 匹配結果容器,支援子捕獲組 `m[1]` |
| `std::regex_search` | 尋找子字串匹配 |
| `std::regex_match` | 整字串完全匹配 |
| `std::regex_replace` | 替換匹配部分 |
| `std::sregex_iterator` | 遍歷所有匹配 |
std::regex_constants::optimize 標誌(編譯時優化自動機)。#include <boost/regex.hpp>
#include <string>
#include <iostream>
int main() {
boost::regex re(R"((\d{4})-(\d{2})-(\d{2}))");
std::string date = "2024-06-15";
boost::smatch m;
if (boost::regex_match(date, m, re)) {
std::cout << "Year: " << m[1] << ", Month: " << m[2] << ", Day: " << m[3] << '\n';
}
}
# C++17 標準庫
g++ -std=c++17 main.cpp -o main
# Boost.Regex 需連結
g++ -std=c++17 main.cpp -o main -lboost_regex