Forward slash in Java Regex

后端 未结 3 1631
甜味超标
甜味超标 2020-12-08 18:24

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

\"Hello/You/There\".replaceAll(\"/\", \"\\\\/\");
  • Expected out
3条回答
  •  不知归路
    2020-12-08 19:13

    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).)

提交回复
热议问题