Forward slash in Java Regex

JavaRegex

Java Problem Overview


I can't figure out why the following code doesn't behave as expected

"Hello/You/There".replaceAll("/", "\\/");
  • Expected output: Hello\/You\/There
  • Actual output: 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.

Java Solutions


Solution 1 - Java

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

(Using java.util.regex.Matcher.quoteReplacement(String).)

Solution 2 - Java

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.

Solution 3 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJuan MendesView Question on Stackoverflow
Solution 1 - JavaruakhView Answer on Stackoverflow
Solution 2 - JavaJames OravecView Answer on Stackoverflow
Solution 3 - Javacoder91View Answer on Stackoverflow