Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Password Validation

I'd like to use regular expression to validate the characters requirement of a password.

Requirement: Password should have 16 characters.

  1. Character 1-4 should have at least 1 digit.
  2. Character 5-8 should have at least 1 lower case character.
  3. Character 9-12 should have at least 1 upper case character.
  4. Character 13-16 should have at least 1 symbol (punctuation).

I've tried to use regular expression with a positive lookahead but it does not work finally:

echo 'XXXX9999ccccXXX%' | grep -P '^((?=.*[0-9]).{4})((?=.*[a-z]).{4})((?=.*[A-Z]).{4})((?=.*\pP).{4})$'

like image 243
idiot one Avatar asked Sep 17 '26 06:09

idiot one


1 Answers

Your lookahead syntax is off, because it is not correctly checking the positions you mentioned in your requirements. The following regex pattern seems to work for me:

^(?=.{0,3}\d)(?=.{4,7}[a-z])(?=.{8,11}[A-Z])(?=.{12,15}[.,$%^&!@]).{16}$

Explanation:

(?=.{0,3}\d)           - number in positions 1-4
(?=.{4,7}[a-z])        - lowercase in positions 5-8
(?=.{8,11}[A-Z])       - uppercase in positions 9-12
(?=.{12,15}[.,$%^&!@]) - symbol in positions 13-16

Demo

I don't know grep or Linux well enough to comment on whether you are making best use, but this should at least fix any problems you were having with the pattern.

like image 124
Tim Biegeleisen Avatar answered Sep 20 '26 03:09

Tim Biegeleisen