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 “]” without “\\”.
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 theA-Zinstead ofA-z).Since both
[and]are included in the rangeA-z, they’re not replaced by yourescapeREmethod.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.