Boost 是 C++ 準標準庫,但 **無預建二進位**,VC6 必須自行編譯。本文記錄 **Boost 1.32.0** 在 VC6 下的編譯步驟、專案整合與正則表達式實戰,助你用上現代 C++ 正則引擎。
cmd
vcvars32.bat // 設定 VC6 環境變數
cd D:\boost_1_32_0\libs\regex\build
d:
nmake -f vc6.mak // 編譯靜態庫 (約 10-30 分鐘,視機器)
nmake -f vc6.mak install // 安裝至 boost 根目錄 stage/lib
#include <boost/regex.hpp>
#include
#include
#include
using namespace std;
using namespace boost;
int main() {
// 編譯期正則 (效能最佳)
regex expr("^select\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s+from\\s+([a-zA-Z_][a-zA-Z0-9_]*)", regex::icase);
string input;
cout << "Enter SQL: ";
getline(cin, input);
cmatch what; // const char* 版本
if (regex_match(input.c_str(), what, expr)) {
cout << "Full match: " << what[0] << endl;
cout << "Column: " << what[1] << endl; // 第一個捕獲組
cout << "Table: " << what[2] << endl; // 第二個捕獲組
} else {
cout << "Invalid SQL format." << endl;
}
return 0;
}
Enter SQL: select name from users Full match: select name from users Column: name Table: users
| 類別 | 用途 | 備註 |
|---|---|---|
basic_regex<CharT> | 正則表達式物件 (編譯後狀態機) | 常用別名:regex (char)、wregex (wchar_t) |
match_results<Iter> | 匹配結果容器 | 常用別名:cmatch (const char*)、smatch (string)、wcmatch/wsmatch |
regex_match | **完整字串** 匹配 | 需滿足整個輸入 |
regex_search | **子字串** 搜尋 | 找到第一個匹配即返回 |
regex_replace | 替換 | 格式化字串支援 `$&` `$1` `$`` `$'` |
regex_iterator | 迭代所有匹配 | 配合 `regex_search` 語意 |
^ $ 行首/尾
. 任意字元 (除換行)
\d \w \s 數字/單字字元/空白
* + ? {n,m} 量詞
() 捕獲組
(?:) 非捕獲組
(?=) (?!) 正/負向前瞻
(?<=) (?
效能優化建議
- 重用 regex 物件:編譯正則昂貴,全域/靜態儲存,避免迴圈內重複建構
- 優先用
regex_match:語意明確,優化機會多
- 避免過度回溯:`(.*)(.*)` 這類模式在長字串會指數爆炸,改用具體字元類別或佔有優先量詞 `*+`
- 啟用優化旗標:`regex::optimize` (編譯較慢、匹配較快)
避坑指南
| 現象 | 原因 | 對策 |
|---|---|---|
| Link error LNK2001: boost::re_detail::... | 未連結 boost_regex.lib | 專案設定加入 library path、Additional dependencies 填 `boost_regex.lib` |
| 編譯錯誤: 'std::allocator' not found | VC6 STL 版本過舊 | 升級 STLPort 或改用 Boost 1.33.1+ (支援 VC6 專用配置) |
| regex_match 總是失敗 | 未轉義反斜線 / 字串字面值雙重轉義 | C++ 字串中 `\` 需寫 `\\`,正則再轉義一次:`\\\\` → 實際 `\\` |
| 中文匹配失敗 | 字元集不匹配 / 未設 locale | 專案設 Unicode、或用 `wregex` + `wstring` + `imbue(locale(""))` |
<regex>:標準庫內建,語法近似 Boost,但 VC6 不支援std::regex + std::string_view:零拷貝匹配在 VC6 這座「時光機」上跑 Boost.Regex,雖然編譯漫長、配置繁瑣,但一旦跑通,**Perl 級正則表達式能力** 即刻到手:SQL 解析、日誌分析、協定解碼、輸入驗證,代碼量減少 80% 以上。若專案允許升級編譯器,**首選標準庫 `