views:

940

answers:

3

Hello guys. am new to regular expression.

I have comma seperated list of regular expressions like: .{8},[0-9],[^0-9A-Za-z ],[A-Z],[a-z]. I have done a split on the comma. Now am trying to match of this regex against a generated password. The problem is that Pattern.compile does not like square brackets that is not escaped. Can some please give me a simple function that takes a string as so: [0-9] and returns the escaped string \[0-9\]. Thanks again

+4  A: 

You can use Pattern.quote(String).

Laurence Gonsalves
+1  A: 

You can use the \Q and \E special characters...anything between \Q and \E is automatically escaped.

\Q[0-9]\E
Dan Breen
Sounds a bit perlish if you ask me, have you tried it in java (I havn't, that's why I ask).
Fredrik
It's valid in Java too: http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html (ctrl-F for "\Q")
MatrixFrog
cool, didn't know that.
Fredrik
In Java string literal format it would be "\\Q[0-9]\\E" or "\\Q" + regex + "\\E". But the quote() method does that for you, plus it deals correctly with strings that already have \E in them.
Alan Moore
A: 

Pattern.compile() likes square brackets just fine. If you take the string

".{8},[0-9],[^0-9A-Za-z ],[A-Z],[a-z]"

and split it on commas, you end up with five perfectly valid regexes: the first one matches eight non-line-separator characters, the second matches an ASCII digit, and so on. Unless you really want to match strings like ".{8}" and "[0-9]", I don't see why you would need to escape anything.

Alan Moore