【问题标题】:Regex or way to replace multiple space with single space正则表达式或用单个空格替换多个空格的方法
【发布时间】:2013-09-21 05:22:01
【问题描述】:

能否请您告诉我有没有办法在java或spring中用单个空格替换多个空格?有相同的 stringUtils 函数吗?

喜欢

1.

test     test
test test

2.

test  test
test test

3.

test                    test
test test

【问题讨论】:

  • 字符串实用程序的问题是它们不会替换可变长度的字符,因此您必须默认为单个字符。但这样做最终会花费大量时间。最好使用正则表达式。

标签: java regex spring


【解决方案1】:

这是@p.s.w.g 的变体 - 它忽略换行符,但仍会得到制表符等。

output = input.replaceAll("[^\\S\\r\\n]+", " ");

【讨论】:

    【解决方案2】:

    替换多个空格

    output = input.replaceAll("[ ]+", " ");
    

    或者替换多个空白字符(包括空格、制表符、换行符等)

    output = input.replaceAll("\\s+", " ");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-07
      • 2018-09-19
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多