boost_1_32_0.zip (解壓後 ~100MB,建置後 ~131MB)vcvars32.batcmd
vcvars32.bat
cd D:\boost_1_32_0\libs\regex\build
d:
nmake -fvc6.mak
nmake -fvc6.mak install
nmake -fvc6.mak:編譯靜態/動態庫 (耗時較久,畫面大量輸出可忽略)nmake -fvc6.mak install:安裝標頭檔與庫檔至 Boost 根目錄D:\boost_1_32_0D:\boost_1_32_0\lib#include "stdafx.h"
#include
#include
#include
#include
#include
using namespace std;
using namespace boost;
// 正則:select 欄位 from 資料表
regex expression("^select ([a-zA-Z]*) from ([a-zA-Z]*)");
int main(int argc, char* argv[]) {
std::string in;
cmatch what;
cout << "enter test string" << endl;
getline(cin, in);
if (regex_match(in.c_str(), what, expression)) {
for (int i = 0; i < what.size(); i++) {
cout << "str :" << what[i].str() << endl;
}
} else {
cout << "Error Input" << endl;
}
return 0;
}
輸入: select name from table
輸出:
str :select name from table
str :name
str :table
what[0] 為完整比對,what[1]、what[2] 為子表達式捕獲組。
| 類別/函式 | 用途 |
|---|---|
boost::regex | 正則表達式物件,建構時編譯模式 |
boost::cmatch | C-字串比對結果容器 |
boost::smatch | std::string 比對結果容器 |
regex_match | 完整字串比對 (需完全符合) |
regex_search | 部分搜尋 (字串中任意位置) |
regex_replace | 替換符合模式的子串 |
what[i].str() | 取得第 i 個捕獲組字串 |
what[i].first/second | 捕獲組迭代器範圍 |
regex 物件避免重複編譯regex::icase:忽略大小寫模式VC6 專案維護建議:
<regex> (VS2010+ 完整支援)std::regex 改良版若專案需長期維護,規劃遷移至現代工具鏈將大幅降低技術債。