How to replace part of a string with special characters

I would like to replace a specific part of the string "\\_\\_\\_\\_\\_"

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

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

I do not see the character "\"in my replaced string, I would expect it to show me"Hello \_\_\_\_\_"

+3
source share
3 answers

You need:

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

Take a look.

\is the escape character in Java strings. So, to denote a literal \, you need to avoid it with another \like \\.

\is an escape char for the regex engine. Thus, a string \\in Java will be sent to the regex engine as \, which is not processed literally, but instead will be used to exit the next character.

\\ regex engine, \\\\ Java.


( ) , , replace String :

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

.

+4

4 , .

: java- - escape-, "\" - . escape-. \ . Java "\\".

, - :

String str = "hello world";
System.out.println(str.replace("world","\\\\_\\\\_\\\\_\\\\"));
+2

.

+1
source

Source: https://habr.com/ru/post/1777895/


All Articles