1

How to replace all "$$$" present in a String?

I tried

story.replaceAll("$$$","\n")

This displays a warning: Anchor $ in unexpected position and the code fails to work. The code takes the "$" symbol as an anchor for a regular expression. I just need to replace that symbol.

Is there any way to do this?

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
Jyoti JK
  • 2,141
  • 1
  • 17
  • 40

4 Answers4

2

"$" is a special character for regular expressions.

Try the following:

    System.out.println(story.replaceAll("\\$\\$\\$", "\n"));

We are escaping the "$" character with a '\' in the above code.

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28
2

There are several ways you can do this. It depends on what you want to do, and how elegant your solution is:

String replacement = "\n"; // The replacement string

// The first way: 
story.replaceAll("[$]{3}", replacement);

// Second way:
story.replaceAll("\\${3}", replacement);

// Third way:
story.replaceAll("\\$\\$\\$", replacement);
Patrick W
  • 1,485
  • 4
  • 19
  • 27
1

You can replace any special characters (Regular Expression-wise) by escaping that character with a backslash. Since Java-literals use the backslash as escaping-character too, you need to escape the backslash itself.

story.replaceAll("\\${3}", something);

By using {3}behind the $, you say, that it should be found exactly three times. Looks a bit more elegant than "\\$\\$\\$". something is thus your replacement, for example "" or \n, depending on what you want.

TreffnonX
  • 2,924
  • 15
  • 23
0

this will surely work..

story.replaceAll("\\$\\$\\$","\n")

YOu can do this for any special character.

SRK
  • 135
  • 8
  • This answer was already provided both in the OP comments and as an actual answer before yours...... – Rann Lifshitz Apr 26 '19 at 05:48
  • @RannLifshitz ,I had typed that answer already and was doing some work and then I submitted.. so it got delayed. :-) – SRK Apr 26 '19 at 05:51