更新时间:2023-02-11 16:41:00
text.replaceAll(";", "");
由于Java中的字符串是不可变的,所以 replaceALl()
方法不进行就地替换,而是返回一个新的修改后的字符串。因此,您需要将返回值存储在其他字符串中。另外,要匹配最后的分号,您需要在之后使用
$
量词;
Since Strings in Java are immutable, so replaceALl()
method doesn't do the in-place replacement, rather it returns a new modified string. So, you need to store the return value in some other string. Also, to match the semi-colon at the end, you need to use $
quantifier after ;
text = text.replaceAll(";$", "");
$
表示自字符串结束你想要替换最后的分号
..
$
denotes the end of the string since you want to replace the last semi-colon
..
如果你不使用 $
,它将替换你的字符串中的所有;
..
If you don't use $
, it will replace all the ;
from your strings..
或,对于你的工作,你可以简单地使用它,如果你想删除最后一个;
:
Or, for your job, you can simply use this, if you want to remove the last ;
:
if (text.endsWith(";")) {
text = text.substring(0, text.length() - 1);
System.out.println(text);
}
更新:并且,如果还有更多半-colons结尾:
UPDATE: And, if there are more semi-colons at the end:
text = text.replaceAll(";+$", "");