我需要在两个或多个连续空格后删除字符串。我试过了:
String.replaceAll(".+$.+$","");
但它不起作用。我需要以下内容:
String = "hi there how are you?"
output:
String = "hi there".
请为上述内容提出一个简单的正则表达式。谢谢。
答案 0 :(得分:1)
答案 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