如何用任意数量的空白替换空白

How do I replace a whitespace with any number of whitespaces?

本文关键字:空白 替换 何用任      更新时间:2023-10-16

我正在尝试使用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+"), "");

这有相同的效果,所以我现在就用它,但它肯定不是理想的!