如何在 Java 中替换字符串中的点(.)

我有一个字符串 persons.name

我想用 /*/代替 DOT .,也就是说我的输出将是 persons/*/name

我试过这个代码:

String a="\\*\\";
str=xpath.replaceAll("\\.", a);

我得到了 StringIndexOutOfBoundsException。

我该怎么替换这个点呢?

139651 次浏览

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

Use Apache Commons Lang:

String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);

or with standalone JDK:

String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

return sentence.replaceAll("\s",".");