Replace all "\\" substring with "\\\\"

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • getmeidea
    New Member
    • Feb 2007
    • 36

    Replace all "\\" substring with "\\\\"

    Hi all,

    String x = "\\";

    This string will have the value \.
    Now for any string contains \, i need to replace with \\.

    But when i use x = x.replaceAll("\ \", "\\\\");
    I am getting runtime exception.

    How can i replace this.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by getmeidea
    Hi all,

    String x = "\\";

    This string will have the value \.
    Now for any string contains \, i need to replace with \\.

    But when i use x = x.replaceAll("\ \", "\\\\");
    I am getting runtime exception.

    How can i replace this.
    You have to double all the backslashes once more because a single backslash
    is not only special to the Java compile (javac), it is also special to the regular
    expression compiler and interpreter.

    kind regards,

    Jos

    Comment

    • BigDaddyLH
      Recognized Expert Top Contributor
      • Dec 2007
      • 1216

      #3
      What Jos writes is true, but let me suggest a simpler solution.

      String has two methods:
      [CODE=Java]
      String replaceAll(Stri ng regex, String replacement)
      String replace(CharSeq uence target, CharSequence replacement)
      [/CODE]
      (CharSequence is an interface implemented by String.) Both methods replace "all occurrences", but method replaceAll is more powerful because it takes a pattern string. However, in your case that just gets in the way because backslash has a special meaning in patterns. So prefer to use the second method unless you really need to use a regular expression pattern:
      [CODE=Java]
      x = x.replace("\\", "\\\\");
      [/CODE]
      Read more about regular expressions here:

      Comment

      Working...