Straight forward slash in Java Regex

I can not understand why the following code is not working properly

"Hello/You/There".replaceAll("/", "\\/"); 
  • Expected Result: Hello\/You\/There
  • Actual output: Hello/You/There

Do I need to hide slashes? I didn’t think so, but I also tried the following against my will ... did not work

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

In the end, I realized that I do not need a regular expression, and I can just use the following, which does not create a regular expression

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

However, I still would like to understand why my first example does not work.

+42
java regex
Mar 05 2018-12-12T00:
source share
3 answers

The problem is that you need to double-reset the backslash in the replacement string. You see, "\\/" (as I'm sure you know) means that the replacement string is \/ , and (as you probably don't know), the replacement string \/ actually just inserts / , because Java is weird, and gives \ special value in the replacement string. (It is assumed that \$ will be a literal dollar sign, but I think the real reason is that they want to communicate with people. Other languages ​​do not do it this way.) So you need to write either:

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

or

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

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

+65
Mar 05 2018-12-12T00:
source share

Double escaping is required when presented as a string.

Whenever I create a new regular expression, I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html

This website allows you to enter a regular expression that it will put out in a string for you, and you can test it on different inputs.

+1
Sep 30 '13 at 15:57
source share

In fact, there is a reason why all these problems are mixed up. A little more digging is done deeper in this topic and it may be useful to understand the reason why "\\" behaves this way.

0
Sep 19 '13 at 11:58 on
source share



All Articles