ReplaceAll () does not remove "|"

3

I have a string "|" and would like to replace with a simple "", my java code in a simplified way looks like this:

String teste = "|A|B|C";
teste.replaceAll("|","");

Output:

"|A|B|C"

I would like the output to be without the "|", I already tested with other normal worked characters, however with that I can not do the replaceAll. Could someone show me another way to remove or the explanation of why this happens?

    
asked by anonymous 24.10.2017 / 12:57

2 answers

8

Need to escape the pipe:

String teste = "|A|B|C";
teste.replaceAll("\|","");

See: link

The pipe is a special character for creating regular expressions, and the replaceXXX methods of java accept regular expressions as arguments. If you do not escape it, it will be interpreted as an E.R. character (conditional value of "OR") and not as a common character.

The two backslashes ( \ ) serve to escape this type of character (not only the pipe but also the period (.), for example) when you want to use them with their nominal value and not as a special character.

    
24.10.2017 / 12:58
3

The first parameter of replaceAll is a regular expression, not a string constant. If you have studied regular expressions correctly, you will know that "|" is a regular expression that matches any character.

Put a "\" in front of "|" , to indicate that "|" is a miserable "|" , not a super-powerful regular expression;

String teste = "|A|B|C";
teste.replaceAll("\|","");
    
24.10.2017 / 13:04