Wednesday, December 14, 2011

Match multiple patterns with a single regex expression

I wanted to add multiple patterns to single regex expression. Such as password check. For example:

* the password has to contain an upper character
* the password has to contain an digit
* the password has to be 8 characters or more.

Here is an example for checking words which contain 'a', 'b' and 'c' characters and are between 10 and 100 characters in length:

^(?=.*a)(?=.*b)(?=.*c)(?=.{10,100}).*$


The example could easily enhanced to match above requirements for passwords.

A real password regex matcher is this one:

^(?=.*[A-Z])(?=.*[0-9])(?=.{7,100}).*$

It filters passwords with length at least 7 characters (and at most 100), which has at least one upper case (English) and at least one digit.

P.S. This is a way of implementing AND operation in regex.

P.S.2. Here is a link to a perfect online regex validator.

No comments:

Post a Comment