在Java中寻找快速、简单的方法来更改此字符串

" hello     there   "

变成了这样的东西

"hello there"

在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。

像这样的事情能让我在一定程度上做到

String mytext = " hello     there   ";
mytext = mytext.replaceAll("( )+", " ");

但事实并非如此。


当前回答

您可以首先使用String.trim(),然后对结果应用regex replace命令。

其他回答

使用Apache commons StringUtils。normalizeSpace(String str)方法。点击这里查看文档

你只需要:

replaceAll("\\s{2,}", " ").trim();

你可以匹配一个或多个空格,用一个空格替换它们,然后在开头和结尾修剪空白(你实际上可以通过先修剪然后匹配来反转正则表达式,就像有人指出的那样)。

要快速测试,请尝试:

System.out.println(new String(" hello     there   ").trim().replaceAll("\\s{2,}", " "));

它会返回:

"hello there"

到目前为止,已经提供了很多正确答案,我看到了很多赞。然而,上面提到的方法可以工作,但不是真正优化或不是真正可读的。 我最近遇到了每个开发人员都会喜欢的解决方案。

String nameWithProperSpacing = StringUtils.normalizeSpace( stringWithLotOfSpaces );

你完成了。 这是一个可读的解。

您可以首先使用String.trim(),然后对结果应用regex replace命令。

"[ ]{2,}"

这将匹配多个空格。

String mytext = " hello     there   ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);

输出:

hello there