我需要在兩個或更多個連續空格後刪除字符串。我曾嘗試過:在java字符串中的兩個空格後刪除文本
String.replaceAll(".+$.+$","");
但它不工作。我需要類似如下:
String = "hi there how are you?"
output:
String = "hi there".
請爲上述建議一個簡單的正則表達式。提前感謝。
我需要在兩個或更多個連續空格後刪除字符串。我曾嘗試過:在java字符串中的兩個空格後刪除文本
String.replaceAll(".+$.+$","");
但它不工作。我需要類似如下:
String = "hi there how are you?"
output:
String = "hi there".
請爲上述建議一個簡單的正則表達式。提前感謝。
所有其他方法將包括\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);
輸出:您好
轉換我的評論來回答。
您可以使用:
str = str.replaceFirst(" {2,}.*$", ""); // only space
或者:
str = str.replaceFirst("\\s{2,}.*$", ""); // all whitespaces
'海峽= str.replaceFirst( 「\\Š{2} * $」, 「」);' – anubhava
@ anubhava非常感謝您的快速回復。它非常完美。 – Suresh