1 Reply Latest reply: Sep 24, 2007 9:24 AM by 807605 RSS

    Pattern... literal interpretation of a String

    567719
      Hi everyone,

      I have googled (with no joy) for a convenience method which would take a String and return a String which can be included as part of a Pattern.compile() as a literal string to match against. Does anybody know of such a utility library that has something like this?

      For example, I'd like to be able to take in a String like "Blah (blah) with blah on the [blah]" and for the output to be "Blah \\(blah\\) with blah on the \\[blah\\]". Given the vast number of special regex characters, I'm certainly not looking to roll out my own version!

      (err... it seems the forums could do with such a utility library as well, it seems that blackslash-blackslash-closing_brace is creating a newline)
        • 1. Re: Pattern... literal interpretation of a String
          807605
          Since JDK 1.5, there are two simple ways to do what you want:
          String safeRegex = Pattern.quote(literalString);
          or
          Pattern p = Pattern.compile(literalString, Pattern.LITERAL);
          If you're still running JDK 1.4, the options are still relatively simple:
          String safeRegex = "\\Q" + literalString + "\\E";
          or
          safeRegex = literalString.replaceAll("\\p{Punct}", "\\\\$0");
          As for the double-backslashes-to-newlines thing, that's a stealth feature that was added to the forums couple of weeks ago. The only known way to circumvent it is to use another stealth feature: wrapping your code in [code] tags before you post it.