1

I tried to replace C:\ to C$ but it is not replace when I used replace method in Java. Is replace method does not accept C:

My string shows C:\Rad\2122\Radn and how to replace C: to C$\Rad\2122\Radn in java.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
testprabhu
  • 63
  • 1
  • 8

3 Answers3

4

I would use replaceFirst, though replace should also work.

path = path.replaceFirst("C:\\\\", "C\\$");

The \ needs to escaped twice, once in the regex and also in the String.

String path = "C:\\path";
path = path.replaceFirst("C:\\\\", "C\\$");
System.out.println(path);

prints

C$path
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • @Pshemo I missed the wanted to replace the \ – Peter Lawrey Jan 19 '16 at 15:22
  • 1
    This will throw `java.lang.IllegalArgumentException: Illegal group reference: group index is missing` because `$x` in replacement represents match from group `x`. For instance `replaceFirst("(.)a","$1$1")` will double character before `a` since `$1` is reference to match from group `1`. If we want to create `$` literal we need to escape it with `"\\$"`. – Pshemo Jan 19 '16 at 15:26
3

Try escaping the \ character

str = str.replace("C:\\", "C$");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Yes, this is the best approach. Regular expressions just add needless complexity to something that can be kept simple. – VGR Jan 19 '16 at 17:34
1
path = "c$" + path.s.substring(2);
sami zahwan
  • 147
  • 4