首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 正則表達式:標準庫 `` 與 Boost.Regex 快速上手指南

     編輯:程式設計綜合問答

現代 C++ (C++11 起) 內建支援

<regex> 提供 ECMAScript 風格正則,語法與 JavaScript 相近。

基本用法

#include <regex>
#include <string>
#include <iostream>

int main() {
    std::string text = "Email: user@example.com, Phone: 0912-345678";
    std::regex email(R"(\b[\w.+-]+@[\w-]+\.[\w.-]+\b)");
    std::regex phone(R"(\b09\d{2}[- ]?\d{3}[- ]?\d{3}\b)");

    // 搜尋第一個匹配
    std::smatch m;
    if (std::regex_search(text, m, email)) {
        std::cout << "Email: " << m[0] << '\n';
    }

    // 遍歷所有匹配
    for (std::sregex_iterator it(text.begin(), text.end(), phone), end; it != end; ++it) {
        std::cout << "Phone: " << it->str() << '\n';
    }

    // 替換
    std::string masked = std::regex_replace(text, email, "[EMAIL]");
    std::cout << masked << '\n';
}

常用類別與函數

類別/函數用途
`std::regex`編譯正則模式物件(昂貴操作,建議重用)
`std::smatch` / `std::cmatch`匹配結果容器,支援子捕獲組 `m[1]`
`std::regex_search`尋找子字串匹配
`std::regex_match`整字串完全匹配
`std::regex_replace`替換匹配部分
`std::sregex_iterator`遍歷所有匹配

效能提示

  • 避免在迴圈中重複建構 `std::regex`;改為 `static const std::regex re(pattern);` 或類別成員。
  • 大量文字處理考慮 std::regex_constants::optimize 標誌(編譯時優化自動機)。
  • 極高效能需求可改用 RE2(線性時間保證)或 Boost.Regex(支援 Perl/PCRE 語法、更豐富功能)。

Boost.Regex 快速範例

#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main() {
    boost::regex re(R"((\d{4})-(\d{2})-(\d{2}))");
    std::string date = "2024-06-15";
    boost::smatch m;
    if (boost::regex_match(date, m, re)) {
        std::cout << "Year: " << m[1] << ", Month: " << m[2] << ", Day: " << m[3] << '\n';
    }
}

編譯連結

# C++17 標準庫
g++ -std=c++17 main.cpp -o main

# Boost.Regex 需連結
g++ -std=c++17 main.cpp -o main -lboost_regex
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved