idiot one
idiot one

Reputation: 389

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})$'

Upvotes: 3

Views: 378

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627302

You may use

^(?=.{0,3}\d).{4}(?=.{0,3}[a-z]).{4}(?=.{0,3}[A-Z]).{4}(?=.{0,3}[\W_]).{4}$

See this demo

Basically, the pattern comprises four lookahead-consuming pattern parts, and since each consuming pattern matches 4 chars, in total, it matches string of 16 chars (note that ^ and $ anchors are also important).

Details

  • ^ - start of string
  • (?=.{0,3}\d) - there must be a digit after 0 to 3 chars
  • .{4} - any 4 chars are consumed
  • (?=.{0,3}[a-z]) - there must be a lowercase letter after 0 to 3 chars
  • .{4} - any 4 chars are consumed
  • (?=.{0,3}[A-Z]) - there must be an uppercase letter after 0 to 3 chars
  • .{4} - any 4 chars are consumed
  • (?=.{0,3}[\W_]).{4} - there must be a special char (non-alphanumeric) after 0 to 3 chars
  • $ - end of string

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522471

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.

Upvotes: 4

Related Questions