2016-11-07 53 views
3

我需要在兩個或更多個連續空格後刪除字符串。我曾嘗試過:在java字符串中的兩個空格後刪除文本

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

但它不工作。我需要類似如下:

String = "hi there how are you?" 

output: 
String = "hi there". 

請爲上述建議一個簡單的正則表達式。提前感謝。

+1

'海峽= str.replaceFirst( 「\\Š{2} * $」, 「」);' – anubhava

+1

@ anubhava非常感謝您的快速回復。它非常完美。 – Suresh

回答

1

您可以利用非貪婪與積極前瞻,以確保一致部分後跟兩個或兩個以上的空格:

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

Demo

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); 

輸出:您好

1

轉換我的評論來回答。

您可以使用:

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

或者:

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