使用std::regex替换前导空格和尾随空格

Replace leading and trailing whitespaces using std::regex?

本文关键字:空格 std regex 替换 使用      更新时间:2023-10-16

我需要删除字符串的前导和尾部空白。它来自tinyxml2的GetText(),其中可能有tn字符,如果我打印出文本,这看起来不太好。

据我所知,这一行是std::regex的正确语法。我已经用在线正则表达式验证了正则表达式。

std::string Printer::trim(const std::string & str)
{
return std::regex_replace(str, std::regex("^s+|s+$"), "", std::regex_constants::format_default);
}

我的理解是,它将用空字符串替换所有前导和尾随空格。这有效地去除了后面和前面的空白。

在传入测试字符串tttnhello worldttn的结果返回字符串tttnhello worldttn,并且输出应该是hello world

我还有一个问题是,c++是否使用与ECMAScript完全相同的regex语法?此外,与使用string.substr()等更传统的方法相比,使用regex会带来什么样的性能成本

我知道还有其他方法可以达到同样的效果,但我计划在项目的其他地方使用std::regex,所以我希望我能想出如何使用它。

您需要对regexp字符串中的反斜杠进行转义,这样它们就会直接传递到regex库。

return std::regex_replace(str, std::regex("^\s+|\s+$"), "", std::regex_constants::format_default);

或者,从C++11开始,您可以使用原始字符串文字:

return std::regex_replace(str, std::regex(R"^s+|s+$"), "", std::regex_constants::format_default);