Search code examples
javaregexposix-ere

How to escape regex text in Java for POSIX Extended format


I want to quote a piece of string to be treated as a literal string inside a larger regex expression, and that expression needs to conform to the POSIX Extended Regular Expressions format.

This question is very similar to this existing question, except that the answer there does not satisfy me since it proposes I use Pattern.quote(), which relies on the special \Q and \E marks - those are supported by Java regexes but do not conform to the POSIX Extended format.

For example, I want one.two to become one\.two and not \Qone.two\E.


Solution

  • The answer by Brian can be simplified to

    String toBeEscaped = "\\{}()[]*+?.|^$";
    return inString.replaceAll("[\\Q" + toBeEscaped + "\\E]", "\\\\$0");
    

    Tested with "one.two" only.