Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceAll "|" by "$" in java

I have tried to replace all "|" by "2" using following code:

 String myString = "I want to change | with 2";
 String trimedString = myString.replaceAll("|", "2");
 System.out.print(trimedString);

My expected output was:

"I want to change | with 2"

But real output was:

"2I2 2w2a2n2t2 2t2o2 2c2h2a2n2g2e2 2|2 2w2i2t2h2 222"

It added 2 before and after each char. What is the correct way of doing this?

like image 842
Shahed Avatar asked Feb 09 '26 17:02

Shahed


1 Answers

You have to insert two backslashes in front of the pipe-symbol in order to escape it.

String myString = "I want to change | with 2";
String trimedString = myString.replaceAll("\\|", "2");
System.out.print(trimedString);
like image 120
xvzwx Avatar answered Feb 12 '26 08:02

xvzwx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!