Let’s say I have multiple requirements for a password. The first is that the password must be 8-20 characters, and the first and last characters must be alpha characters, and the middle characters are any combination of alpha-numerics, mixed with a few symbols. The expression I’ve managed to come up with so far is:
^[a-zA-Z]{1}[a-zA-Z0-9#$!&*@()]{6,18}[a-zA-Z]{1}$
This works fine, but now the requirement is that I have to have at least 1 upper case character, at least one lower case character, at least one digit, and at least one of the characters mentioned.
How do I combine these requirements into a single expression such that I can simulate something like:
If(Regex.IsMatch(“^[a-zA-Z]{1}[a-zA-Z0-9#$!&*@()]{6,18}[a-zA-Z]{1}$”, userInput) // Check most of the conditions (starts with alpha, ends with alpha, and is 8-20 characters total)
&& Regex.IsMatch(“[A-Z]”, userInput) // Ensure there’s an upper case
&& Regex.IsMatch(“[a-z]”, userInput) // Ensure there’s a lower case
&& Regex.IsMatch(“[0-9]”, userInput) // Ensure there’s a digit
&& Regex.IsMatch(“[#$!&*@()]”) // Ensure there’s an allowed symbol
)
{
// Do something here
}
I understand the OR operator is just |, but is there a simple way to “AND” conditions together? If not, what’s the recommended approach?
I recommend writing several test as you have done. The compound regex that you propose is opaque to the point of obscurity, and so difficult to debug and maintain. If you insist on keeping it all in a single regex, then I suggest you use the
/xmodifier (theIgnorePatternWhitespaceoption in MS C++) so that you can use whitespace to make it legible, and use zero-width lookaheads for your assertions, like this