【问题标题】:Replace leading and trailing whitespaces using std::regex?使用 std::regex 替换前导和尾随空格?
【发布时间】:2018-04-11 19:57:18
【问题描述】:

我需要删除字符串的前导和尾随空格。它来自 tinyxml2 中的 GetText(),其中可以包含 \t\n 字符,如果我打印出文本看起来不太好。

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

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

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

传入测试字符串\t\t\t\nhello world\t\t\n 的结果返回字符串\t\t\t\nhello world\t\t\n,输出应该是hello world

我的另一个问题是 c++ 是否使用与ECMAScript 完全相同的正则表达式语法?此外,使用正则表达式而不是更传统的方法(例如使用string.substr())会产生什么样的性能成本

我知道还有其他方法可以实现相同的效果,但我计划在项目的其他地方使用std::regex,所以我希望我能弄清楚如何使用它。

【问题讨论】:

  • 转义反斜杠。
  • 对不起,我不明白你的意思? @Barmar
  • \\s 而不是 \s

标签: c++ regex string c++11


【解决方案1】:

您需要转义正则表达式字符串中的反斜杠,以便将它们按字面意思传递给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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 2019-12-16
    • 1970-01-01
    • 2012-02-28
    相关资源
    最近更新 更多