Why is there no AND for regular expressions?

Here’s a Javascript regular expression which will match a string which contains at least one lower case letter:

/[a-z]/

And another which will match a string with at least one upper case character:

/[A-Z]/

I can even stick these together in at least two ways to create the equivalent of a logical OR – in other words a string will match if it contains at least one lower case letter OR at least one upper case letter:

/[a-zA-Z]/
/([a-z]|[A-Z])/

What seems to be missing is a simple way of concatenating two regular expressions (and, by extension, more than two) such that the target string has to match every sub-expression for the result to be a match. Other than calling regex.test() once for each sub-expression, I can’t see any simple way to AND several regular expressions together like this.

It’s a shame really, because I’d love to be able to do something like this, to make sure that the user has selected a password of between 8 and 16 characters, which must contain at least one numeral, and which may optionally contain some punctuation characters (using the & character to AND together the terms):

var bIsComplexPass = /(.{8,16})&([0-9])&([!"£$%^@~#]*)/.test("[email protected]");

Leave a Reply

Your email address will not be published. Required fields are marked *