VC6 內建無標準正則表達式庫,常見方案有:VBScript.RegExp COM 元件、Microsoft GRETA、或第三方 **Boost.Regex**。Boost 為標準 C++ 庫,效能優異、語法符合 Perl/ECMAScript、支援分組/後向引用。本文詳細記錄 Boost 1.34.0 在 VC6 下的編譯、安裝、專案設定與測試全流程。
rem 假設解壓至 C:\boost_1_34_0
cd /d C:\boost_1_34_0\libs\regex\build
call "C:\Program Files\Microsoft Visual Studio\VC98\Bin\vcvars32.bat"
rem 編譯 Release 版靜態庫 + DLL
nmake -fvc6.mak
rem 輸出位置:C:\boost_1_34_0\libs\regex\build\vc6\
rem 產生:boost_regex-vc6.lib, boost_regex-vc6.dll, .pdb 等
rem 將 lib 複製到 VC98\Lib,dll 複製到 VC98\Bin
nmake -fvc6.mak install
或手動複製:
boost_regex-vc6.lib → C:\Program Files\Microsoft Visual Studio\VC98\Lib\boost_regex-vc6.dll → C:\Program Files\Microsoft Visual Studio\VC98\Bin\C:\boost_1_34_0boost_regex-vc6.lib#include <boost/regex.hpp>
#include <string>
#include <iostream>
using namespace std;
using namespace boost;
int main()
{
// 模式:yyyy-mm-dd (注意 C++ 字串需雙重轉義)
regex expression("\\d{4}-\\d{2}-\\d{2}");
string input = "Today: 2007-06-23";
cmatch what;
// regex_search: 在字串中搜尋符合模式的子串
if (regex_search(input.c_str(), what, expression)) {
for (int i = 0; i < what.size(); ++i) {
cout << "match[" << i << "]: " << what[i].str() << endl;
}
} else {
cout << "未找到符合日期格式的字串" << endl;
}
return 0;
}
match[0]: 2007-06-23
match[1]: 2007
match[2]: 06
match[3]: 23
| 問題 | 解決 |
|---|---|
| 連結錯誤 LNK2001: 未解析的外部符號 | 確認 Link 設定有加入 boost_regex-vc6.lib,且 Runtime Library 設定一致 (MD/MDd)。 |
| 執行時找不到 DLL | 將 boost_regex-vc6.dll 放入專案輸出目錄或系統 PATH 目錄 (如 VC98\Bin)。 |
編譯錯誤: regex.hpp 找不到 | Include 目錄必須指向 Boost 根目錄 (含 boost/ 子目錄),而非 boost/regex。 |
| Debug 版連結 Release 版庫 | Boost 1.34 vc6.mak 預設只建 Release;若需 Debug 請修改 Makefile 或手動建置 Debug 版。 |
發布程式時,**必須隨附 boost_regex-vc6.dll** (約 300KB+),建議放在應用程式同目錄下,避免 DLL Hell。
Boost.Regex 為 VC6 專案引入現代正則表達式能力的最佳選擇。雖編譯安裝稍繁瑣,但一次設定長期受益,語法標準、效能優異、支援 Unicode (搭配 wregex),極大提升字串解析開發效率。