[java] How to Replace dot (.) in a string in Java

I have a String called persons.name

I want to replace the DOT . with /*/ i.e my output will be persons/*/name

I tried this code:

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

I am getting StringIndexOutOfBoundsException.

How do I replace the dot?

This question is related to java str-replace

The answer is


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",".");