Match regex in any order

后端 未结 2 1273
梦毁少年i
梦毁少年i 2021-01-13 02:14

I want to check for complex password with regular expression.

It should have 1 number 1 uppercase and one lowercase letter, not in specific order. So i though about

相关标签:
2条回答
  • 2021-01-13 03:01

    You could have tried looking for password validating regex, the site has a lot of them ;)

    That said, you can use positive lookaheads to do that:

    re.search(r"(?=.*[a-z])(?=.*[A-Z])(?=.*\d)", "1Az")
    

    And to actually match the string...

    re.search(r"(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{3}", "1Az")
    

    And now, to ensure that the password is 3 chars long:

    re.search(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{3}$", "1Az")
    

    A positive lookahead (?= ... ) makes sure the expression inside is present in the string to be tested. So, the string has to have a lowercase character ((?=.*[a-z])), an uppercase character ((?=.*[A-Z])) and a digit ((?=.*\d)) for the regex to 'pass'.

    0 讨论(0)
  • 2021-01-13 03:10

    Why not just:

    if (re.search(r"[a-z]", input) and re.search(r"[A-Z]", input) and re.search(r"[0-9]", input)):
        # pass
    else
        # don't pass
    
    0 讨论(0)
提交回复
热议问题