5

I have a java.lang.String that may contain any character possible, is there a easy way to sanitize the string (for example with an additional class that can do that?) and remove all "dangerous" characters for a later java.util.regex.Matcher or regex processing (e.g. $, ^, ...)?

Robert Heine
  • 1,820
  • 4
  • 29
  • 61
  • Too complicated to do it, consider using your string as argument of Pattern.match(string) instead of parsing your string – morgano Jun 27 '13 at 08:00
  • 1
    Would quoting them also be ok? http://stackoverflow.com/questions/60160/how-to-escape-text-for-regular-expression-in-java – Bart Kiers Jun 27 '13 at 08:01

2 Answers2

16

You can use

Pattern.quote(string);

to escape your string for Regex.

hsz
  • 148,279
  • 62
  • 259
  • 315
5

You can also use \Q..\Eescape sequence.

Here is an example for Metacharacters Inside Character Classes.

Any thing inside \Q..\E pair is considered as literal.

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
  • 2
    There's a risk of `\E` being part of the string, which will terminate the escape sequence. You're safe using hsz's answer. – jlordo Jun 27 '13 at 08:12