re2 C++ replace (GlobalReplace) 最小示例

此最小示例展示如何使用 re2 GlobalReplace() 函数替换字符串:

re2_globalreplace_example.cpp
#include <re2/re2.h>
#include <iostream>
#include <string>

using namespace re2;
using namespace std;

// 预编译正则表达式
RE2 myRegex("\\$[^\\$]+\\$");

int main(int argc, char** argv) {
    string myString = "This string $abc123$ contains two formulas $123 != 456$.";
    // 注意:这会修改 myString!
    RE2::GlobalReplace(&myString, myRegex, "FORMULA");
    // 打印 "This string FORMULA contains two formulas FORMULA."
    cout << myString << endl;
}

Check out similar posts by category: C/C++, Regex