1

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?

CanSpice
  • 34,814
  • 10
  • 72
  • 86
itun
  • 3,439
  • 12
  • 51
  • 75
  • 1
    possible duplicate of [How to escape text for regular expression in Java](http://stackoverflow.com/questions/60160/how-to-escape-text-for-regular-expression-in-java) - It looks like you're trying to implement `Pattern#quote()`. – Matt Ball Sep 16 '11 at 20:21

1 Answers1

7

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.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288