VC6 缺乏標準正則表達式庫,ATL::CAtlRegExp 僅支援 VC7+,COM 介面 (VBScript.RegExp) 效能差且部署麻煩。Boost.Regex 是跨平台、高效能、標準 C++ 的最佳選擇,本文詳述 VC6 下從下載、編譯、設定到實戰的完整流程。
boost_1_34_0.zip(當前穩定版)C:\boost_1_34_0cd C:\boost_1_34_0\libs\regex\build
vcvars32.bat // 設定 VC6 環境變數
nmake -fvc6.mak // 編譯產生 lib/pdb/dll 於 build\vc6
nmake -fvc6.mak install // 自動複製 lib 至 VC98\lib、dll 至 VC98\bin
注意:原始碼壓縮包不大,但編譯後佔用 100MB+,請預留空間。發布程式時需攜帶 boost_regex-vc6.dll。
C:\boost_1_34_0boost_regex-vc6.lib(install 步驟已自動置於庫目錄)#include
#include
#include
#include
#include
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
// 正則:三組數字以 - 分隔,括號為捕獲群組
regex expression("(\\d+)-(\\d+)-(\\d+)"); // 注意雙重跳脫
string input(" Today: 2007-06-23 ");
cmatch what; // const char* 版本匹配結果
// regex_search:在字串中搜尋符合模式的子字串
// regex_match:要求整個字串完全符合(適合驗證輸入)
if (regex_search(input.c_str(), what, expression))
{
for (int i = 0; i < what.size(); ++i)
{
cout << " str : " << what[i].str() << endl;
}
}
return 0;
}
str : 2007-06-23
str : 2007
str : 06
str : 23
what[0] 為完整匹配,what[1..3] 為三個捕獲群組(年/月/日)。
| 需求 | API / 技巧 |
|---|---|
| 替換字串 | regex_replace(str, expr, "格式"),格式中 $1 參考群組 |
| 分割字串 | sregex_token_iterator 配合 -1 參數 |
| Unicode 支援 | 使用 wregex, wstring, wcmatch |
| 效能優化 | 編譯期建構 static const regex 避免重複編譯模式 |
| 錯誤處理 | 捕獲 boost::regex_error 例外 |
微軟研究院開源的 GRETA 同樣支援 VC6/VC7,模板實現、無外部相依,適合不想引入 Boost 巨大庫的專案。
Boost.Regex 雖編譯步驟稍繁,但一次設定長期受益,提供工業級正則引擎、完整 Perl 相容語法、Unicode 支援與極佳效能。VC6 專案若需字串解析、驗證、擷取,首選 Boost.Regex。