Vikas Singh
Vikas Singh

Reputation: 3038

replacing '\\' string with '\' in java

Hi we have a string like "ami\\303\\261o". we want to replace \\ with \.

We have tried the following:

  1. replace("\\", "\")
  2. replaceAll("\\", "\")

But we didn't get proper output.

Upvotes: 2

Views: 154

Answers (5)

Rais Alam
Rais Alam

Reputation: 7016

Try below code

 String val = "ami\\303\\261o"; 
    val =val.replaceAll("\\\\", "\\\\");        
    System.out.println(val);

Outpout would be

ami\303\261o

A Fiddle is created here check it out

Java Running Example

Upvotes: 0

SimonSez
SimonSez

Reputation: 7769

Thats because the \\ inside your input String get internally replaced by \ because of the Java Escape Character.
That means that if you output your String without performing any regex on it, it would look like this: "ami\303\261o".

Generally you should remember to escape every escape-character with itself:

\ -> escaped = \\  
\\ -> escaped = \\\\  
\\\ -> escaped = \\\\\\  
...and so on  

Upvotes: 0

tschiela
tschiela

Reputation: 5271

No need of regex here. Escape the slashes and use replace()

someString.replace('\\\\', '\\');

Upvotes: 3

Olaf Dietsche
Olaf Dietsche

Reputation: 74108

You must keep backslash escaping in mind. Use

public class so {
    public static void main(String[] args) {
        String s = "ami\\\\303\\\\261o";
        System.out.println(s);
        s = s.replace("\\\\", "\\");
        System.out.println(s);
    }
};

Each backslash escapes the following backslash and resolves to the two literal strings \\ and \

Also keep in mind, String.replace returns the modified string and keeps the original string intact.

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

For use in a Java regex, you need to escape the backslashes twice:

resultString = subjectString.replaceAll("\\\\\\\\", "\\\\");
  1. In a regex, \\ means "a literal backslash".
  2. In a Java string, "\\" encodes a single backslash.
  3. So, a Java string that describes a regex that matches a single backslash is "\\\\"
  4. And if you want to match two backslashes, it's "\\\\\\\\", accordingly.

Upvotes: 3

Related Questions