【问题标题】:Regex to replace all occurrences between two matches正则表达式替换两个匹配项之间的所有匹配项
【发布时间】:2016-05-04 02:06:02
【问题描述】:

我正在使用std::regex,需要进行搜索和替换。

我的字符串是:

begin foo even spaces and maybe new line(
some text only replace foo foo bar foo, keep the rest
)
some more text not replace foo here

只应触摸begin .... () 之间的内容。

我设法通过使用此搜索和替换替换了第一个 foo:

(begin[\s\S]*?\([\s\S]*?)foo([\s\S]*?\)[\s\S]*)

$1abc$2

Online regex demo

Online C++ demo

但是,如何一次性替换所有三个 foo? 我尝试了环视,但由于量词而失败。

最终结果应如下所示:

begin foo even spaces and maybe new line(
some text only replace abc abc bar abc, keep the rest
)
some more text not replace foo here

问题更新:

我正在寻找一个纯正则表达式解决方案。也就是说,问题应该只通过更改the online C++ demo中的searchreplace字符串来解决。

【问题讨论】:

  • 最终结果应该是什么样子?
  • 也许获取括号之间的文本并全部替换会更容易?然后你重建字符串。
  • @Thomas 有,仔细阅读。
  • @Revolver_Ocelot 该死的复制/粘贴错误。谢谢。

标签: c++ regex std


【解决方案1】:

我想出了这段代码(基于Benjamin Lindley's answer):

#include <iostream>
#include <regex>
#include <string>
int main()
{
    std::string input_text = "my text\nbegin foo even 14 spaces and maybe \nnew line(\nsome text only replace foo foo bar foo, keep the rest\n)\nsome more text not replace foo here";
    std::regex re(R"((begin[^(]*)(\([^)]*\)))");
    std::regex rxReplace(R"(\bfoo\b)");
    std::string output_text;
    auto callback = [&](std::string const& m){
        std::smatch smtch;
        if (regex_search(m, smtch, re)) {
            output_text += smtch[1].str();
            output_text += std::regex_replace(smtch[2].str().c_str(), rxReplace, "abc");
        } else {
            output_text += m;
        }
    };

    std::sregex_token_iterator
        begin(input_text.begin(), input_text.end(), re, {-1,0}),
        end;
    std::for_each(begin,end,callback);

    std::cout << output_text;
    return 0;
}

IDEONE demo

我正在使用一个正则表达式来查找 begin...(....) 的所有匹配项并将它们传递到回调函数中,其中仅进一步处理第 2 组(\bfoo\b 正则表达式用于将 foos 替换为 abcs) .

我建议使用(begin[^(]*)(\([^)]*\)) 正则表达式:

  • (begin[^(]*) - 组 1 匹配字符序列 begin 后跟零个或多个字符,而不是 (
  • (\([^)]*\)) - 第 2 组匹配文字 (,后跟零个或多个字符,而不是 )(带有 [^)]*)和文字 )

【讨论】:

  • 嗨,谢谢。我正在寻找一个纯正则表达式解决方案。我已经在代码中解决了这个问题,但我更希望将所有逻辑都放在一个正则表达式中。我会更新我的问题以使其更清楚。但无论如何都是不错的解决方案!
  • 不能使用 std::regex。它不支持 \G 运算符,也不支持无限宽度的后视。
猜你喜欢
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2013-08-05
相关资源
最近更新 更多