Bill Kindig
Bill Kindig

Reputation: 3622

Regex check length in range

These are the requirements:

I currently have this expression, which works as expected:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

This checks for everything except length, so this is valid Aa2@

How do I add the length check of 12-16 characters?

Upvotes: 3

Views: 806

Answers (1)

anubhava
anubhava

Reputation: 784958

Your regex is:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

Those are set of lookahead assertions to enforce certain rules of your requirements. However that regex is not consuming any characters in the match and that's where you can use .{12,16} or \S{12,16} range quantifier to restrict input to 12 to 16 characters. So following solutions should work for you:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)\S{12,16}$
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W).{12,16}$
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)(?=.{12,16}$)
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)(?=\S{12,16}$)

A . will match any character but \S matches a non-whitespace character only.

Upvotes: 5

Related Questions