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.
replaceAll("/", "\\/");
The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
String regex = "\\."; Notice that the regular expression String contains two backslashes after each other, and then a . . The reason is, that first the Java compiler interprets the two \\ characters as an escaped Java String character. After the Java compiler is done, only one \ is left, as \\ means the character \ .
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)
.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With