Reputation: 3038
Hi we have a string like "ami\\303\\261o"
. we want to replace \\
with \
.
We have tried the following:
replace("\\", "\")
replaceAll("\\", "\")
But we didn't get proper output.
Upvotes: 2
Views: 154
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
Upvotes: 0
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
Reputation: 5271
No need of regex here. Escape the slashes and use replace()
someString.replace('\\\\', '\\');
Upvotes: 3
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
Reputation: 336468
For use in a Java regex, you need to escape the backslashes twice:
resultString = subjectString.replaceAll("\\\\\\\\", "\\\\");
\\
means "a literal backslash"."\\"
encodes a single backslash."\\\\"
"\\\\\\\\"
, accordingly.Upvotes: 3