开发者

Escape special symbols from regexpr

I use this code:

static Pattern escaper = Pattern.compile("([^a-zA-z0-9])");

public static String escapeRE(String str) {
    return escaper.matcher(str).replaceAll("\\\\$1");
}

It works pretty, until I don't use this string: "[". I looked in the debuger the result is "]" with开发者_开发技巧out "\\".

System.out.println(Main.escapeRE("+"));
System.out.println(Main.escapeRE(">="));
System.out.println(Main.escapeRE("]"));
System.out.println(Main.escapeRE("["));

Result:

\\+
\\>\\=
]
[

Why it is so?


Your character class [^a-zA-z0-9] is incorrect. It should be: [^a-zA-Z0-9] (note the A-Z instead of A-z).

Since both [ and ] are included in the range A-z, they're not replaced by your escapeRE method.

EDIT

As @Matt mentioned in the comments: if you're trying to escape regex-meta-chars, have a look at the Pattern.quote(String) method which is created especially for this purpose.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜