使用std::regex替换前导空格和尾随空格
Replace leading and trailing whitespaces using std::regex?
我需要删除字符串的前导和尾部空白。它来自tinyxml2的GetText()
,其中可能有t
和n
字符,如果我打印出文本,这看起来不太好。
据我所知,这一行是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);
相关文章:
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- C++命令末尾的 std::stringstream 空格
- 当输入 1 个没有空格的名称时,它会显示"std::out_of_range"
- C++ [std::regex] 尝试仅匹配中间有空格的数字
- std::string 上的 substr 无法正常工作,因为存在一些不可见但看起来像空格的字符
- std::wistringstream在解析时可以忽略字符串中的空格吗
- 使用std::regex替换前导空格和尾随空格
- std::没有等价关系的唯一示例(删除连续空格)
- 初始化模板<size_t N> std::array<char, N> 带有 ASCII 空格?
- 为什么这个 leveldb 代码会截断包含空格的"std::string"?
- 为什么 std::operator>>(istream&, char&) 提取空格?
- 读取STD :: String Line(带有空格和特殊钥匙支持)
- 如何在Windows上使用std::system运行带有空格的可执行文件
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- std::cin 跳过空格
- std::getline 删除空格
- std::stringstream 不读取空格
- 有没有一种不使用std::getline从文件中读取空格的方法?
- std::ws(空格)在读取数据时的作用
- 为什么在Windows上std::fopen和std::filebuf::open会裁剪尾随空格字符