Search code examples
javastringreplaceall

String's replace all is replacing none


I have the following code:

System.out.println("Trace: #" +"2");
System.out.println(rv); 
        rv.replaceAll("$t",sTAB);
System.out.println("Trace: #" +"3");
System.out.println(rv); 

The rv and sTAB are of type String. And sTAB has a value of a tab character. The output is as follows:

Trace: #2
is$thi$t
Trace: #3
is$thi$t

But I expect:

Trace: #2
is$thi$t
Trace: #3
is{tab}hi{tab}    

Of course with {tab} being actual tab characters. Can you explain what is wrong with my code?


Solution

  • replaceAll() takes a regular expression and returns the replaced String.

    $ is a regular expression meta character that matches the end of a line.

    Try using:

    rv = rv.replaceAll("\\$t", sTAB);