首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ Boost.Regex 正則表達式完整實戰指南:從安裝到進階應用

     編輯:關於C++

什麼是正則表達式?

正則表達式 (Regular Expression, Regex) 是描述文字模式的強大工具。Boost.Regex 提供 C++ 標準庫級的正則支援,語法預設為 Perl 相容 (PCRE),亦支援 POSIX Extended/Basic。

環境建置:Boost.Regex 編譯與整合

原始碼編譯 (VC6 範例)

cmd
vcvars32.bat
cd D:\boost_1_32_0\libs\regex\build
d:
nmake -fvc6.mak
nmake -fvc6.mak install

注意:解壓縮後 ~100MB,編譯後 ~131MB,需預留空間與時間。

VS2003 批次檔範例

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

IDE 整合

  • VC6: Tools → Options → Directories → Include files 加入 Boost 根目錄
  • 專案設定 → Linker → Input 加入 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);

實戰範例解析

基本匹配:解析 SQL 片段

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);  // 不區分大小寫

Unicode 支援

  • 需編譯時啟用 ICU (International Components for Unicode)
  • wregex:支援 UTF-16/UTF-32 (視 wchar_t 大小)
  • u32regex:明確支援 UTF-32
  • 注意:wregex 不支援 UTF-8,UTF-8 需用 u8regex 或轉碼後處理

match_results 詳細結構

匹配成功時:

  • 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 編譯優化 (編譯較慢、匹配較快)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved