3

I would like to replace a certain portion of the string with "\\_\\_\\_\\_\\_"

(e.g. String str = "Hello World")

If I do str.replaceAll("World", "\\_\\_\\_\\_\\_");

I don't see the "\" character in my replaced string, I would expect it to show me "Hello \_\_\_\_\_"

codaddict
  • 445,704
  • 82
  • 492
  • 529
Achaius
  • 5,904
  • 21
  • 65
  • 122

3 Answers3

4

You need:

str = str.replaceAll("World", "\\\\_\\\\_\\\\_\\\\_\\\\_");

See it.

\ is the escape character in Java strings. So to mean a literal \ you need to escape it with another \ as \\.

\ is the escape char for the regex engine as-well. So a \\ in Java string will be sent to regex engine as \ which is not treated literally but instead will be used to escape the following character.

To pass \\ to regex engine you need to have \\\\ in the Java string.


Since you are replacing a string (not pattern) with another string, there is really no need for regex, you can use the replace method of the String class as:

input = input.replace("World", "\\_\\_\\_\\_\\_");

See it.

codaddict
  • 445,704
  • 82
  • 492
  • 529
2

You need to use 4 backslashes to insert a single one.

The point is: in literal java strings the backslash is an escape character so the literal string "\" is a single backslash. But in regular expressions, the backslash is also an escape character. The regular expression \ matches a single backslash. This regular expression as a Java string, becomes "\\".

So try something like this:

String str = "hello world";
System.out.println(str.replace("world","\\\\_\\\\_\\\\_\\\\"));
Bogdan
  • 412
  • 1
  • 3
  • 14
1

Have a look at this post.

Community
  • 1
  • 1
FrVaBe
  • 47,963
  • 16
  • 124
  • 157