90

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?

1
  • I know that's an old question, but ad advice for everyone getting here: please, stop using replaceAll where you do not have to deal with regex. "replaceAll" doesn't mean "replace all occurrencies", in Java libraries.
    – Andrea
    Feb 17 at 10:45

4 Answers 4

158

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)

1
  • 2
    shouldn't it be xpath.replaceAll("\\\\.", "/*/") ?
    – ha9u63a7
    Sep 29, 2017 at 12:20
18

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(".", "/*/");
0
9

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);
-2

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

1
  • 2
    This is not what the question is asking for.
    – khelwood
    Jun 16, 2021 at 10:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.