首页 文章

正则表达式验证密码强度

提问于
浏览
116

我的密码强度标准如下:

  • 长度为8个字符
    大写

  • 2个字母

  • 1特殊字符 (!@#$&*)

  • 2个数字 (0-9)

  • 小写字母3个字母

有人可以给我正则表达式 . 密码必须满足所有条件 .

9 回答

  • 0

    对于PHP,这很好用!

    if(preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2}).{8,}$/", 
     'CaSu4Li8')){
        return true;
     }else{
        return fasle;
     }
    

    在这种情况下,结果是真的

    @ridgerunner的问题

  • 367

    您可以使用正向预测断言进行这些检查:

    ^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$
    

    Rubular link

    说明:

    ^                         Start anchor
    (?=.*[A-Z].*[A-Z])        Ensure string has two uppercase letters.
    (?=.*[!@#$&*])            Ensure string has one special case letter.
    (?=.*[0-9].*[0-9])        Ensure string has two digits.
    (?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
    .{8}                      Ensure string is of length 8.
    $                         End anchor.
    
  • 2

    您可以使用零长度正向预测来分别指定每个约束:

    (?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!@#$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})
    

    如果您的正则表达式引擎不支持 \p 表示法并且纯ASCII足够,那么您可以将 \p{Lu} 替换为 [A-Z] 并将 \p{Ll} 替换为 [a-z] .

  • 9

    上面给出的答案是完美的,但我建议使用多个较小的正则表达式而不是大的正则表达式 .
    拆分长正则表达式有一些优点:

    • 易于书写和阅读

    • 易于调试

    • 容易添加/删除部分正则表达式

    通常这种方法保留代码 easily maintainable .

    话虽如此,我分享了一段我在 Swift 中编写的代码:

    struct RegExp {
    
        /**
         Check password complexity
    
         - parameter password:         password to test
         - parameter length:           password min length
         - parameter patternsToEscape: patterns that password must not contains
         - parameter caseSensitivty:   specify if password must conforms case sensitivity or not
         - parameter numericDigits:    specify if password must conforms contains numeric digits or not
    
         - returns: boolean that describes if password is valid or not
         */
        static func checkPasswordComplexity(password password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool {
            if (password.length < length) {
                return false
            }
            if caseSensitivty {
                let hasUpperCase = RegExp.matchesForRegexInText("[A-Z]", text: password).count > 0
                if !hasUpperCase {
                    return false
                }
                let hasLowerCase = RegExp.matchesForRegexInText("[a-z]", text: password).count > 0
                if !hasLowerCase {
                    return false
                }
            }
            if numericDigits {
                let hasNumbers = RegExp.matchesForRegexInText("\\d", text: password).count > 0
                if !hasNumbers {
                    return false
                }
            }
            if patternsToEscape.count > 0 {
                let passwordLowerCase = password.lowercaseString
                for pattern in patternsToEscape {
                    let hasMatchesWithPattern = RegExp.matchesForRegexInText(pattern, text: passwordLowerCase).count > 0
                    if hasMatchesWithPattern {
                        return false
                    }
                }
            }
            return true
        }
    
        static func matchesForRegexInText(regex: String, text: String) -> [String] {
            do {
                let regex = try NSRegularExpression(pattern: regex, options: [])
                let nsString = text as NSString
                let results = regex.matchesInString(text,
                    options: [], range: NSMakeRange(0, nsString.length))
                return results.map { nsString.substringWithRange($0.range)}
            } catch let error as NSError {
                print("invalid regex: \(error.localizedDescription)")
                return []
            }
        }
    }
    
  • 1

    我建议补充一下

    (?!.*pass|.*word|.*1234|.*qwer|.*asdf) exclude common passwords
    
  • 0

    codaddict的解决方案工作正常,但这个效率更高一些:( Python语法)

    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)
    

    被否定的字符类在一个步骤中消耗所有字符,需要零回溯 . (点星解决方案工作得很好,但确实需要一些回溯 . )当然,对于密码等短目标字符串,这种效率提升可以忽略不计 .

  • 0
    import re
    
    RegexLength=re.compile(r'^\S{8,}$')
    RegexDigit=re.compile(r'\d')
    RegexLower=re.compile(r'[a-z]')
    RegexUpper=re.compile(r'[A-Z]')
    
    
    def IsStrongPW(password):
        if RegexLength.search(password) == None or RegexDigit.search(password) == None or RegexUpper.search(password) == None or RegexLower.search(password) == None:
            return False
        else:
            return True
    
    while True:
        userpw=input("please input your passord to check: \n")
        if userpw == "exit":
            break
        else:
            print(IsStrongPW(userpw))
    
  • 0

    另一种方案:

    import re
    
    passwordRegex = re.compile(r'''(
        ^(?=.*[A-Z].*[A-Z])                # at least two capital letters
        (?=.*[!@#$&*])                     # at least one of these special c-er
        (?=.*[0-9].*[0-9])                 # at least two numeric digits
        (?=.*[a-z].*[a-z].*[a-z])          # at least three lower case letters
        .{8,}                              # at least 8 total digits
        $
        )''', re.VERBOSE)
    
    def userInputPasswordCheck():
        print('Enter a potential password:')
        while True:
            m = input()
            mo = passwordRegex.search(m) 
            if (not mo):
               print('''
    Your password should have at least one special charachter,
    two digits, two uppercase and three lowercase charachter. Length: 8+ ch-ers.
    
    Enter another password:''')          
            else:
               print('Password is strong')
               return
    userInputPasswordCheck()
    
  • 6

    密码必须满足以下4个复杂性规则中的至少3个,

    [至少1个大写字母(A-Z)至少1个小写字符(a-z)至少1个数字(0-9)至少1个特殊字符 - 不要忘记将空格视为特殊字符]

    至少10个字符

    最多128个字符

    连续不超过2个相同的字符(例如,111不允许)

    '^(?! . ( . )\ 1 {2})((?= . [az])(?= . [AZ])(?= . [0-9])|(?= . [az] )(= [AZ])(= [^A-ZA-Z0-9])|?????(= [AZ])(= [0-9])(= [^一个-Za-Z0-9])|?(= [AZ])(= [0-9])(= * [^A-ZA-Z0-9])){10127} $”?? .

    (?! . *( . )\ 1 {2})

    (?= [A-Z])(?= [A-Z])(?= . * [0-9])

    (?= [A-Z])(?= [A-Z])(?= . * [^A-ZA-Z0-9])

    (?= [A-Z])(?= . [0-9])(?= . * [^A-ZA-Z0-9])

    (?= [A-Z])(?= . [0-9])(?= . * [^A-ZA-Z0-9])

    {} 10.127

相关问题