如何用任意数量的空白替换空白
How do I replace a whitespace with any number of whitespaces?
我正在尝试使用boost::regex
构建一个正则表达式(我的GCC版本不能处理std::regex
特别好)。
我想用s*
替换任何出现的空白,以便它匹配任何数量的空白(我不在乎空白的数量是否不同)。
下面是一个例子:
std::string s = "this is a test string";
s = boost::regex_replace(s, boost::regex("\s+"), "\s*");
std::cout << s;
这产生:
这场* iss * * *测试字符串;
我想要的是thiss*iss*as*tests*string
。为什么这不起作用?
我试着用\\s*
替换,但这只是产生this\s*is\s*a\s*test\s*string
,也不是我所追求的!
在这种情况下,您似乎没有从使用正则表达式中获得很多好处。有一个(可能是次要的)附带条件,没有它们也很容易做到这一点(尽管将结果与字符串匹配将非常需要正则表达式)。
std::string input = "this is a test string";
std::istringstream buffer(input);
std::ostringstream result;
std::copy(std::istream_iterator<std::string>(buffer),
std::istream_iterator<std::string>(),
infix_ostream_iterator<std::string>(result, "\s*"));
std::cout << result.str();
Result: thiss*iss*as*tests*string
.
使用另一篇文章中的infix_ostream_iterator
。
附带条件:这(目前)不尝试处理结果模式的开始和/或结束处的空白。在大多数情况下,这些都不是必需的,但是如果您想添加它们,那么这样做非常简单。
这不是一个非常令人满意的解决方案,但根据评论,我认为这可能是我的boost
版本(1.53)的问题。为了解决这个问题,我只需要删除所有的空白空间:
stringToMatch = boost::regex_replace(stringToMatch, boost::regex("\s+"), "");
expression = boost::regex_replace(expression, boost::regex("\s+"), "");
这有相同的效果,所以我现在就用它,但它肯定不是理想的!
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 无法通过空白将文本文件行分隔为矢量
- 如何用转义符替换字符串中的所有特殊字符
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 在一个读写器队列中,我可以用volatile替换原子吗
- 用符号版本替换对函数的所有调用
- 由cin中的字符串中未捕获空白引起的分割错误
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 替换基于地图的所有引用
- 按平均值替换数组中的元素
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 初始化 std::vector 替换为单大括号而不是双大括号
- 如何创建一个程序来替换单个空白/选项卡的多个空白/选项卡
- 将utf8编码的字符串转换为本地8位编码的字符串,并将无法确定的字符替换为空白
- 如何使用c++将字符串中出现的空白替换为下划线
- 将空白字符替换为 %20 的字符串,忽略所有尾随空格
- 如何用任意数量的空白替换空白
- 替换wxString, c++中的空白
- 在调用函数c++之后,用另一个字符替换空白