Java 正则表达式或用单个空格替换多个空格的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18838532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:31:43  来源:igfitidea点击:

Regex or way to replace multiple space with single space

javaregexspring

提问by Adam

Could you please let me know is there any way to replace multiple space with single space in java or spring? Any stringUtils function for same?

您能否让我知道有什么方法可以用 java 或 spring 中的单个空格替换多个空格?任何 stringUtils 函数相同吗?

like

喜欢

1.

1.

test     test
test test

2.

2.

test  test
test test

3.

3.

test                    test
test test

回答by p.s.w.g

To replace multiple spaces

替换多个空格

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

Or replace multiple whitespace characters (including space, tab, new line, etc.)

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

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

回答by p.s.w.g

This is a variation of @p.s.w.g - it ignores newlines, but still get tabs and such.

这是@pswg 的一种变体——它忽略换行符,但仍然获得制表符等。

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

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