How do I replace the a portion of the string with special characters
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 \_\_\_\_\_"
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.
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","\\\\_\\\\_\\\\_\\\\"));
Have a look at this post.
精彩评论