Regex to validate password strength

后端 未结 11 959
天涯浪人
天涯浪人 2020-11-22 02:13

My password strength criteria is as below :

  • 8 characters length
  • 2 letters in Upper Case
  • 1 Special Character (!@#$&*)
  • <
11条回答
  •  孤城傲影
    2020-11-22 02:57

    codaddict's solution works fine, but this one is a bit more efficient: (Python syntax)

    password = re.compile(r"""(?#!py password Rev:20160831_2100)
        # Validate password: 2 upper, 1 special, 2 digit, 1 lower, 8 chars.
        ^                        # Anchor to start of string.
        (?=(?:[^A-Z]*[A-Z]){2})  # At least two uppercase.
        (?=[^!@#$&*]*[!@#$&*])   # At least one "special".
        (?=(?:[^0-9]*[0-9]){2})  # At least two digit.
        .{8,}                    # Password length is 8 or more.
        $                        # Anchor to end of string.
        """, re.VERBOSE)
    

    The negated character classes consume everything up to the desired character in a single step, requiring zero backtracking. (The dot star solution works just fine, but does require some backtracking.) Of course with short target strings such as passwords, this efficiency improvement will be negligible.

提交回复
热议问题