我想替换xx*为x.
我试过了string.replaceAll("xx*", "x");
但是在正则表达式*中很特殊,所以我需要给出一个\*
但\在 java 中给出一个我需要给出\\
==> 最后它应该与string.replaceAll("xx\\*", "x");
但是当字符串包含xx*上述语句时,无法替换 xx*为x
您必须将replaceAll()调用结果重新分配给字符串变量 - 该方法返回一个新字符串,而不是修改您调用它的字符串。
不要用replaceAll()!!replace()在处理文字字符串时使用:
string = string.replace("xx*", "x");
字符串是不可变的。将结果赋给replaceAll原始值
string = string.replaceAll("xx\\*", "x");
string.replaceAll("xx\\*", "x")不会更改给定的字符串,因为字符串在 Java 中是不可变的。您需要使用返回的值,例如将其分配回原始变量:string = string.replaceAll("xx\\*", "x")