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. $, ^, ...)?
Asked
Active
Viewed 2,343 times
5

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
-
1Would 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 Answers
5
You can also use \Q..\E
escape 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
-
2There'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