Reputation: 389
I'd like to use regular expression to validate the characters requirement of a password.
Requirement: Password should have 16 characters.
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
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 stringUpvotes: 1
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
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