Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8144811

regex.Matcher.quoteReplacement doesn't quote '&' inside the replacement string

XMLWordPrintable

      A DESCRIPTION OF THE REQUEST :
      I was using a replacement string that contained regex special chars like '$', '\' , '&' that needed to be used literally. I used quoteReplacement on that string. The method did escape the '$\' chars but didn't escape the '&', so the replacement treated it as a regex variable and replace the whole string properly. While the doc clearly says that quoteReplacement escapes only '$\' - I had to use extra escaping for the '&' char.

      JUSTIFICATION :
      It would be nice to avoid an extra replaceAll on a string. If there is a method that is supposed to take care of escaping special chars then it should be all chars that are special for regex.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      quoteReplacement should escape '&' as well as '$' and '\'. Possibly other special chars too.
      ACTUAL -
      quoteReplacement doesn't escape '&'.

      ---------- BEGIN SOURCE ----------

      String s = "Dogs and cats are lovely pets but cost some money to see a vet"
      s= s.replaceAll("money", Matcher.quoteReplacement("$")); // works
      s= s.replaceAll("and", Matcher.quoteReplacement("&")); // doesn't
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      s= s.replaceAll("and", Matcher.quoteReplacement("\\\\&"));

            rgiulietti Raffaello Giulietti
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: