正則表達式 (Regular Expression, Regex) 是描述文字模式的強大工具。Boost.Regex 提供 C++ 標準庫級的正則支援,語法預設為 Perl 相容 (PCRE),亦支援 POSIX Extended/Basic。
cmd
vcvars32.bat
cd D:\boost_1_32_0\libs\regex\build
d:
nmake -fvc6.mak
nmake -fvc6.mak install
注意:解壓縮後 ~100MB,編譯後 ~131MB,需預留空間與時間。
chdir E:\Program\boost_1_34_1
bjam "-sTOOLS=vc-7_1" "-sVC71_ROOT=D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7"
"--prefix=E:\Program\boost" "--builddir=E:\Program\boost_1_34_1\build"
"-sBUILD=debug release <runtime-link>static/dynamic" --with-regex install
libboost_regex.lib (或 debug 版)| 類別/類型 | 用途 | 常用別名 |
|---|---|---|
basic_regex | 儲存編譯後正則模式 | regex (char), wregex (wchar_t) |
sub_match | 單一匹配結果 (迭代器對) | - |
match_results | 匹配結果容器 | cmatch, wcmatch, smatch, wsmatch |
// 1. 完整匹配
bool regex_match(const string&, match_results&, const basic_regex&);
// 2. 部分搜尋
bool regex_search(const string&, match_results&, const basic_regex&);
// 3. 格式化替換
string regex_format(const string&, const match_results&, const string& fmt);
regex expr("^select ([a-zA-Z]*) from ([a-zA-Z]*)");
cmatch what;
if (regex_match(input.c_str(), what, expr)) {
for (int i=0; i
bool validate_card_format(const string& s) {
static const regex e(R"((\d{4}[- ]){3}\d{4})"); // 原始字串字面值 C++11
return regex_match(s, e);
}
regex e1(pattern); // 預設區分大小寫
regex e2(pattern, regex::perl | regex::icase); // 不區分大小寫
wregex:支援 UTF-16/UTF-32 (視 wchar_t 大小)u32regex:明確支援 UTF-32wregex 不支援 UTF-8,UTF-8 需用 u8regex 或轉碼後處理匹配成功時:
m[0]:完整匹配字串m[1]...m[n]:第 1~n 個捕獲群組 (對應正則中 () 順序)m.prefix():匹配前的前綴m.suffix():匹配後的後綴m.size() == re.mark_count():群組數 = 捕獲括號數 + 1// regex_iterator: 產出 match_results
for (sregex_iterator it(s.begin(), s.end(), re), end; it != end; ++it) {
cout << (*it)[0] << endl; // 完整匹配
}
// regex_token_iterator: 產出 sub_match (單一群組)
for (sregex_token_iterator it(s.begin(), s.end(), re, 1), end; it != end; ++it) {
cout << *it << endl; // 第 1 群組
}
輸入:實際值/-20.031,-1.896,-2.861,-1,0,0
regex exp(R"(\s*實際值/(-?[0-9.]+),(-?[0-9.]+),(-?[0-9.]+),(-?[0-9.]+),(-?[0-9.]+),(-?[0-9.]+)$)");
smatch m;
if (regex_match(text, m, exp)) {
for (int i=1; i
優化建議:使用 (-?[\d.]+) 簡化,或 (-?\d+(?:\.\d+)?) 嚴格限制數值格式。
| 語法 | 說明 |
|---|---|
. | 任意字元 (預設不含換行) |
^ / $ | 行首 / 行尾 |
* / + / ? | 0或多 / 1或多 / 0或1 |
{n} / {n,} / {n,m} | 精確n / 至少n / n到m次 |
| | 或運算 |
[abc] / [a-z] / [^a-z] | 字元集 / 範圍 / 排除 |
() | 捕獲群組 |
(?:) | 非捕獲群組 |
static const regex) 避免重複編譯regex_iterator 串流處理string::find 或 string_view 替代regex::optimize 編譯優化 (編譯較慢、匹配較快)