开发者

Escape special symbols from regexpr

开发者 https://www.devze.com 2023-04-05 05:33 出处:网络
I use this code: static Pattern escaper = Pattern.compile(\"([^a-zA-z0-9])\"); public static String escapeRE(String str) {

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

精彩评论

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