【发布时间】: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