'How to replace "\" with "/" in java? [duplicate]
I have a string like s = "abc\def" and I want to replace "" with "/" and makes the string like "abc/def/".
I tried replaceAll("\\","/")
but the compiler is giving error for string
error: illegal escape character String s="abc\def";
Solution 1:[1]
The issue is that Java uses \
as the string escape character, but also as the regex escape character, and replaceAll
performs a regex search. So you need to doubly escape the backslash (once to make it a literal \
in the string, and once to make it a literal character in the regular expression):
result = str.replaceAll("\\\\", "/");
Alternatively, you don’t actually need regular expressions here, so the following works as well:
result = str.replace("\\", "/");
Or, indeed, using the single-char replacement version:
result = str.replace('\\', '/');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |