C++11 <regex> 在 GCC 4.8.1 未完整支援,需使用 Boost.Regex。安裝參考:Boost 安裝指南。編譯需連結 -lboost_regex。
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main() {
// 模式:非 'c' 字元後接 'ei',前後可有任意字母
std::string pattern("[^c]ei");
pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
boost::regex r(pattern, regex::icase); // 忽略大小寫
std::string str("Ruby Carolinei biubiubiu Weindy SpikeI Winnceiy");
// sregex_iterator 遍歷所有匹配
for (boost::sregex_iterator it(str.begin(), str.end(), r), end_it;
it != end_it; ++it) {
std::cout << it->str() << std::endl;
}
std::cout << std::endl;
// 輸出匹配前後文脈
for (boost::sregex_iterator it(str.begin(), str.end(), r), end_it;
it != end_it; ++it) {
auto pos = it->prefix().length();
pos = pos > 40 ? pos - 40 : 0;
std::cout << it->prefix().str().substr(pos) // 前文
<< "\n\t\t>>>" << it->str() // 匹配部分
<< "<<<\n"
<< it->suffix().str().substr(0, 40) // 後文
<< std::endl;
}
// 子表達式匹配:檔案名解析
std::string filename("File.cqp MyGod.cpP");
boost::regex rsub("([[:alnum:]]+)\\.(cpp|cxx|cc)$", regex::icase);
smatch results;
if (boost::regex_search(filename, results, rsub)) {
std::cout << results.str(1) << std::endl; // 第 1 子表達式
}
}
Carolinei Weindy SpikeI Ruby >>>Carolinei<<< biubiubiu Weindy SpikeI Winnceiy biubiubiu >>>Weindy<<< SpikeI Winnceiy >>>SpikeI<<< Winnceiy MyGod
| 類別/方法 | 用途 |
|---|---|
boost::regex | 編譯正則模式,支援 icase 等旗標 |
boost::sregex_iterator | 字串正則迭代器,遍歷所有匹配 |
match_results::prefix() | 匹配前的子字串 |
match_results::suffix() | 匹配後的子字串 |
match_results::str(n) | 第 n 子表達式內容 (0=整體) |
boost::regex_search | 搜尋單次匹配,填充 smatch |
使用括號 () 分組,str(1) 存取第一組,以此類推。應用於資料驗證、解析結構化文本(如檔案名、日期、電話號碼)。