How to escape text for regular expression in Java

前端 未结 8 1813
我在风中等你
我在风中等你 2020-11-22 03:30

Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter \"$5\", I\'d like to match that exa

8条回答
  •  旧巷少年郎
    2020-11-22 03:42

    First off, if

    • you use replaceAll()
    • you DON'T use Matcher.quoteReplacement()
    • the text to be substituted in includes a $1

    it won't put a 1 at the end. It will look at the search regex for the first matching group and sub THAT in. That's what $1, $2 or $3 means in the replacement text: matching groups from the search pattern.

    I frequently plug long strings of text into .properties files, then generate email subjects and bodies from those. Indeed, this appears to be the default way to do i18n in Spring Framework. I put XML tags, as placeholders, into the strings and I use replaceAll() to replace the XML tags with the values at runtime.

    I ran into an issue where a user input a dollars-and-cents figure, with a dollar sign. replaceAll() choked on it, with the following showing up in a stracktrace:

    java.lang.IndexOutOfBoundsException: No group 3
    at java.util.regex.Matcher.start(Matcher.java:374)
    at java.util.regex.Matcher.appendReplacement(Matcher.java:748)
    at java.util.regex.Matcher.replaceAll(Matcher.java:823)
    at java.lang.String.replaceAll(String.java:2201)
    

    In this case, the user had entered "$3" somewhere in their input and replaceAll() went looking in the search regex for the third matching group, didn't find one, and puked.

    Given:

    // "msg" is a string from a .properties file, containing "" among other tags
    // "userInput" is a String containing the user's input
    

    replacing

    msg = msg.replaceAll("", userInput);
    

    with

    msg = msg.replaceAll("", Matcher.quoteReplacement(userInput));
    

    solved the problem. The user could put in any kind of characters, including dollar signs, without issue. It behaved exactly the way you would expect.

提交回复
热议问题