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.
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.replaceAll in this case - replace is much clearer.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.
No need of regex here. Escape the slashes and use replace()
someString.replace('\\\\', '\\');
' with ".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
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
String val = "ami\\303\\261o"; System.out.println(val); The output is still ami\303\261o.
"ami\\303\\261o"the "real" string or the string literal in Java ?\is the escape character, so\\will produce a literal backslash. So the string will actually only contain\, not\\. How exactly do you want the result to look like?\where not rendered properly. I did not change the content of string or code (see the markdown side-by-side comparison).