如何在C++ RE2库中基于正则匹配结果动态确定替换字符串
C++ RE2库实现自定义正则替换(foo与bar互换)
RE2库没有原生支持传入回调的替换接口,我们可以通过手动遍历匹配项的方式实现需求,全程仅需一次文本扫描,不会出现两次替换互相覆盖的问题,实现代码如下:
#include <iostream> #include <string> #include "re2/re2.h" int main() { // 定义正则规则,分组1匹配foo,分组2匹配bar const re2::RE2 regex("(foo)|(bar)"); std::string input = "some texts to edit foo bar foo bar"; std::string result; // 记录上一次匹配结束的位置 size_t last_match_end = 0; // 存储两个捕获组的匹配结果 re2::StringPiece foo_group, bar_group; re2::StringPiece input_piece(input); while (RE2::FindAndConsume(&input_piece, regex, &foo_group, &bar_group)) { // 计算当前匹配项的起始位置 size_t match_start = input.size() - input_piece.size() - (foo_group.empty() ? bar_group.size() : foo_group.size()); // 追加上一次匹配结束到本次匹配开始之间的未匹配内容 result.append(input, last_match_end, match_start - last_match_end); // 根据匹配到的分组追加对应替换值 if (!foo_group.empty()) { result += "bar"; } else { result += "foo"; } // 更新匹配结束位置 last_match_end = input.size() - input_piece.size(); } // 追加最后剩余的未匹配内容 result.append(input, last_match_end); // 输出结果:some texts to edit bar foo bar foo std::cout << result << std::endl; return 0; }
代码核心逻辑说明:
RE2::FindAndConsume会自动移动输入字符串的扫描指针,每次匹配成功后从下一个字符继续查找- 通过判断两个捕获组是否为空,即可确定当前匹配到的是foo还是bar,直接替换即可
- 全程仅扫描一次文本,不存在两次替换导致的结果回退问题
内容的提问来源于stack exchange,提问作者Berkay Berabi
相关产品推荐
相关产品推荐

