开发者

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 Ex开发者_如何学Gopressions 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.


Maybe something along these lines:

// 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();
}


The answer by Brian can be simplified to

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

Tested with "one.two" only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜