boost::regex_replace 依據正則模式替換字串,支援格式化字串 $n 參照子表達式。可選參數控制輸出行為:format_no_copy 僅輸出替換結果,不複製未匹配部分。
#include <iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main() {
// 電話號碼模式(同前例)
std::string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ]?)(\\d{4})";
boost::regex r(phone);
// 替換格式:$2=區號 $5=前3碼 $7=後4碼,以 . 連接
std::string fmt("$2.$5.$7");
// 單一號碼替換
std::string number("(908)555-1800");
std::cout << regex_replace(number, r, fmt) << std::endl;
// 輸出: 908.555.1800
// 字串中多處替換
std::string file("Caroline (201)555-2368 862-55-0123");
std::cout << boost::regex_replace(file, r, fmt) << std::endl;
// 輸出: Caroline 201.555.2368 862-55-0123
// 僅輸出替換結果(不複製未匹配部分)
std::cout << boost::regex_replace(file, r, fmt,
boost::regex_constants::format_no_copy) << std::endl;
// 輸出: 201.555.2368
}
908.555.1800 Caroline 201.555.2368 862-55-0123 201.555.2368
| 語法 | 含義 |
|---|---|
$n | 第 n 個子表達式內容 (n=1-9) |
$& | 整個匹配字串 |
$` | 匹配前的字串 |
$' | 匹配後的字串 |
$$ | 字面 $ 符號 |
format_default:預設,複製未匹配部分 + 替換匹配部分format_no_copy:僅輸出替換結果format_first_only:僅替換第一次匹配format_sed:sed 風格語法(s/pattern/replacement/)${var} → $1