Home > database >  Regex check length in range
Regex check length in range

Time:09-23

These are the requirements:

  • 1 Uppercase
  • 1 Lowercase
  • 1 Special character
  • 1 Number (0-9)
  • Total length is 12-16

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?

CodePudding user response:

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.

  • Related