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

C++ 正則表達式迭代器完整指南:Boost.Regex 遍歷與子表達式

     編輯:關於C++

Boost.Regex 環境設定

C++11 <regex> 在 GCC 4.8.1 未完整支援,需使用 Boost.Regex。安裝參考:Boost 安裝指南。編譯需連結 -lboost_regex。

迭代器遍歷完整範例

#include <iostream>
#include <string>
#include <algorithm>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;

int main() {
    // 模式:非 'c' 字元後接 'ei',前後可有任意字母
    std::string pattern("[^c]ei");
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
    
    boost::regex r(pattern, regex::icase);  // 忽略大小寫
    std::string str("Ruby Carolinei biubiubiu Weindy SpikeI Winnceiy");
    
    // sregex_iterator 遍歷所有匹配
    for (boost::sregex_iterator it(str.begin(), str.end(), r), end_it; 
         it != end_it; ++it) {
        std::cout << it->str() << std::endl;
    }
    
    std::cout << std::endl;
    
    // 輸出匹配前後文脈
    for (boost::sregex_iterator it(str.begin(), str.end(), r), end_it; 
         it != end_it; ++it) {
        auto pos = it->prefix().length();
        pos = pos > 40 ? pos - 40 : 0;
        std::cout << it->prefix().str().substr(pos)  // 前文
                  << "\n\t\t>>>" << it->str()       // 匹配部分
                  << "<<<\n" 
                  << it->suffix().str().substr(0, 40)  // 後文
                  << std::endl;
    }
    
    // 子表達式匹配:檔案名解析
    std::string filename("File.cqp MyGod.cpP");
    boost::regex rsub("([[:alnum:]]+)\\.(cpp|cxx|cc)$", regex::icase);
    smatch results;
    if (boost::regex_search(filename, results, rsub)) {
        std::cout << results.str(1) << std::endl;  // 第 1 子表達式
    }
}

輸出結果分析

Carolinei
Weindy
SpikeI

Ruby >>>Carolinei<<< biubiubiu Weindy SpikeI Winnceiy
biubiubiu >>>Weindy<<< SpikeI Winnceiy
>>>SpikeI<<< Winnceiy

MyGod

關鍵類別與方法

類別/方法用途
boost::regex編譯正則模式,支援 icase 等旗標
boost::sregex_iterator字串正則迭代器,遍歷所有匹配
match_results::prefix()匹配前的子字串
match_results::suffix()匹配後的子字串
match_results::str(n)第 n 子表達式內容 (0=整體)
boost::regex_search搜尋單次匹配,填充 smatch

子表達式分組

使用括號 () 分組,str(1) 存取第一組,以此類推。應用於資料驗證、解析結構化文本(如檔案名、日期、電話號碼)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved