Avoiding Regular Expression Text in Java for POSIX Extended Format

I want to give a fragment of a string that will be considered as a literal string inside a larger regular expression, and this expression should match the POSIX Extended Regular Expressions .

This question is very similar to this existing question , except that the answer there does not satisfy me, as it suggests using Pattern.quote()one that relies on a special one \Qand \Ethose that are supported by Java regular expressions but do not conform to the POSIX Extended format.

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

+3
source share
2 answers

Brian's answer can be simplified to

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

Tested with only "one.two".

+2
source

Maybe something like that:

// untested
String escape(String inString)
{
    StringBuilder builder = new StringBuilder(inString.length() * 2);
    String toBeEscaped = "\\{}()[]*+?.|^$";

    for (int i = 0; i < inString.length(); i++)
    {
        char c = inString.charAt(i);

        if (toBeEscaped.contains(c))
        {
            builder.append('\\');
        }

        builder.append(c);
    }

    return builder.toString();
}
+3
source

Source: https://habr.com/ru/post/1794936/


All Articles