Replace "\" with any other character using String replace ()

I cannot perform a simple operation with String, replace \ with *.

Example: t'est\'t'est*

I tried with replacing and replacing all methods:

String s has the meaning: "t'est\'" ;

 s.replaceAll("\'", "*"); -> result: t*est* s.replaceAll("\\'", "*"); -> result: t*est* s.replaceAll("\\\'", "*"); -> result: t*est* s.replaceAll("\\\\'", "*"); -> result: t'est' s.replace("\'", "*"); -> result: t'est' s.replace("\\'", "*"); -> result: t'est' s.replace("\\\'", "*"); -> result: t'est' s.replace("\\\\'", "*"); -> result: t'est' 

But I do not get the result t'est * in any case.

+8
java string replace special-characters
source share
6 answers

Are you sure the value of s ? ' not a significant escape character, so if you write String s = "t'est\'" , the value of s will simply be "t'est'" . To add an extra \ character, you need to avoid it by writing String s = "t'est\\'" . Then, I think that "\\\\'" will be a regular expression to search for it.

+9
source share

What about:

 String s="t\'est\\\'"; s = s.replaceAll("\\\\'", "*"); System.out.println(s); 

gives:

 t'est* 

I escaped from your line using http://www.htmlescape.net/javaescape_tool.html

+1
source share

\' is actually shielded ' . If you want to have the actual 'you need to avoid the slash, namely write \\\'

Then you will need to replace it with \\\\' . In this case, each pair of slashes results in a single escaped slash \ for java, and the resulting \\' is \' for the regular expression.

+1
source share

How about this

 String s = "t'est\\'"; System.out.println(s); System.out.println(s.replace("\\", "*").replace("*'", "*")); 

Here is the result:

 t'est\' t'est* 

Let me know if my understanding is wrong or if it needs modifications.

+1
source share

You do not need to run 'Just write

 s.replace("'", "*"); 

to replace '


Edit:

If you want to combine \ ', you should try

 s.replace("\\'", "*"); 

The first backslash will escape the second, and "remain" without saving "

0
source share

When you say that String s has the value "t'est", do you mean how it appears in the source? Because if this is the case, the line you are working with as "s" is actually "t'est", which means that you will never find the replaced "\".

If it is declared as "t'est \", then it will have a "\" in it.

0
source share

All Articles