删除java字符串中两个空格后的文本

时间:2016-11-07 03:32:07

标签: java regex

我需要在两个或多个连续空格后删除字符串。我试过了:

String.replaceAll(".+$.+$","");

但它不起作用。我需要以下内容:

String = "hi there  how are you?" 

output:
String = "hi there".

请为上述内容提出一个简单的正则表达式。谢谢。

3 个答案:

答案 0 :(得分:1)

你可以利用积极前瞻的非贪婪来确保匹配的部分后跟两个或更多的空格:

^.*?(?=\\s{2,})

Demo

答案 1 :(得分:1)

所有其他方法都包括\r\n\t\f\v。因为你只想要2 spaces,所以我认为你不想要。在这种情况下更容易使用substring

    String a = "hi there  how are you?"; 
    if (a.indexOf("  ") > 0) a = a.substring(0, a.indexOf("  "));
    System.out.println(a);

输出嗨那里

答案 2 :(得分:1)

将我的评论转换为答案。

您可以使用:

str = str.replaceFirst(" {2,}.*$", ""); // only space

或者:

str = str.replaceFirst("\\s{2,}.*$", ""); // all whitespaces