Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

前端 未结 30 3788
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 04:28

I want a regular expression to check that:

A password contains at least eight characters, including at least one number and includes both lower and uppercase letter

30条回答
  •  春和景丽
    2020-11-21 05:16

    Not directly answering the question, but does it really have to be a regex?

    I used to do lots of Perl, and got used to solving problems with regexes. However, when they get more complicated with all the look-aheads and other quirks, you need to write dozens of unit tests to kill all those little bugs.

    Furthermore, a regex is typically a few times slower than an imperative or a functional solution.

    For example, the following (not very FP) Scala function solves the original question about three times faster than the regex of the most popular answer. What it does is also so clear that you don't need a unit test at all:

    def validatePassword(password: String): Boolean = {
      if (password.length < 8)
        return false
    
      var lower = false
      var upper = false
      var numbers = false
      var special = false
    
      password.foreach { c =>
        if (c.isDigit)       numbers = true
        else if (c.isLower)  lower = true
        else if (c.isUpper)  upper = true
        else                 special = true
      }
    
      lower && upper && numbers && special
    }
    

提交回复
热议问题