I can't figure out why the following code doesn't behave as expected
"Hello/You/There".replaceAll("/", "\\/");
Hello\/You\/There
Hello/You/There
Do I need to escape forward slashes? I didn't think so but I also tried the following against my will ... didn't work
"Hello/You/There".replaceAll("\\/", "\\/");
In the end I realized I don't need a regular expression and I can just use the following, which doesn't create a regular expression
"Hello/You/There".replace("/", "\\/");
However, I'd still like to understand why my first example doesn't work.
There is actually a reason behind why all these are messed up. A little more digging deeper is done in this thread and might be helpful to understand the reason why "\\" behaves like this.
Double escaping is required when presented as a string.
Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html
That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.
Source: Stackoverflow.com