首页 > 解决方案 > 如何使用非捕获组在标记之间用 std::regex_replace 替换空格?

问题描述

我正在尝试使用正则表达式消除字符串中的空格。从以下代码段:

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++regexc++11g++regex-group

解决方案


如果><被捕获,它们可以被写回。
这样就没有断言兼容性问题。

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

代替

$1(newcontent)$2

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


推荐阅读