【问题标题】:How do I replace spaces with std::regex_replace between markers using non-capture groups?如何使用非捕获组在标记之间用 std::regex_replace 替换空格?
【发布时间】:2021-12-14 18:23:18
【问题描述】:

我正在尝试使用正则表达式消除字符串中的空格。来自以下sn-p:

std::string in = "abc>  <def\n"
                 "xyz>      \n";
std::regex re = R"((?:>)\s+(?:<)|\s+$)";
std::string out = std::regex_replace(in, re, "(newcontent)");

我期待out 包含

abc>(newcontent)<def
xyz>(newcontent)

但是,唉,我明白了

abc(newcontent)def
xyz>(newcontent)

相反。对我来说,非捕获序列(?:...) 似乎不起作用。我尝试将扩展名修改为std::regex re ("....", std::regex::ECMAScript | std::regex::nosubs); 并将, std::regex_constants::format_default 附加到regex_replace 无济于事。这可能是库实现问题还是我有错?

【问题讨论】:

    标签: c++ regex c++11 g++ regex-group


    【解决方案1】:

    如果&gt;&lt; 被捕获,它们可以被写回。
    这样就不存在断言兼容性问题。

    (>)\s+(<)|\s+$
    

    替换

    $1(newcontent)$2
    

    https://regex101.com/r/dOjUlw/1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      相关资源
      最近更新 更多