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


87

我有一个字符串叫做 persons.name

我想./*/ 我的输出替换DOTpersons/*/name

我尝试了这段代码:

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

我正在获取StringIndexOutOfBoundsException。

如何更换圆点?

Answers:



9

使用Apache Commons Lang

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

或独立JDK:

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

7

如果您要替换一个简单的字符串并且不需要正则表达式的功能,则可以使用replace,而不是replaceAll

replace 替换每个匹配的子字符串,但不将其参数解释为正则表达式。

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.