Replaceall() does not remove "|"

Asked

Viewed 127 times

5

I have a following string "|" and I would like to replace it with a simple "", my java code is like this:

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

Exit:

"|A|B|C"

I would like the output to be without "|", I have tested with other characters worked normal, but with this I can not do replaceAll. Could someone show me another way to withdraw or explain why this happens?

2 answers

8


You need to escape the pipe:

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

Behold: https://ideone.com/haskam

The pipe is a special character to create regular expressions, and the methods replaceXXX java accepts regular expressions as argument. If you do not escape it, it will be interpreted as a character of E.R.(conditional value of "OR") and not as a common character.

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

3

The first parameter of replaceAll is a regular expression, not a string constant. If you’ve studied regular expressions properly, you’ll know that "|" is a regular expression that matches any character.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.