1 Reply Latest reply on Sep 24, 2007 2:24 PM by 807605

    Pattern... literal interpretation of a String

      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
          Since JDK 1.5, there are two simple ways to do what you want:
          String safeRegex = Pattern.quote(literalString);
          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";
          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.