简体   繁体   English

正则表达式验证字符串包含字母和数字而不考虑特殊字符

[英]Regex validate string contains letters and numbers regardless of special characters

For password validation in Python, I need to make a regex, which validates that passwords contains both letters and numbers.对于 Python 中的密码验证,我需要制作一个正则表达式,用于验证密码是否同时包含字母和数字。 I have this regex:我有这个正则表达式:

re.match(r"^[A-Za-z]+\d+.*$", password)

But if the password contains a special character, then it won't pass.但如果密码包含特殊字符,则不会通过。 So password for example "MyPassword6" will be ok but "MyPassword-6" not.因此,例如“MyPassword6”的密码可以,但“MyPassword-6”则不行。 Also it will not pass if number is on the beginning "6MyPassword".如果数字在开头“6MyPassword”上,它也不会通过。

How to validate a regex with mandatory letters and numbers regardless of their order and regardless of the presence of other special characters?如何使用强制性字母和数字验证正则表达式,而不管它们的顺序如何以及是否存在其他特殊字符?

Thank you!!!谢谢!!!

adding [~!@#$%^& ()_-] didn't help and I can't find other solution:/添加[~!@#$%^& ()_-] 没有帮助,我找不到其他解决方案:/

This regular expression uses two positive lookahead assertions (?=...) to ensure that the password contains at least one letter and at least one number.此正则表达式使用两个正向先行断言(?=...)来确保密码至少包含一个字母和至少一个数字。 The .* symbol in each lookahead assertion means that any characters, including special characters and whitespace can be present in the password, as long as the letters and numbers are also present.每个先行断言中的.*符号表示密码中可以包含任何字符,包括特殊字符和空格,只要字母和数字也存在即可。

import re

# compile the regular expression
regex = re.compile(r'(?=.*[a-zA-Z])(?=.*[0-9])')

def is_valid_password(password):
    # Check if the password is valid
    return regex.search(password) is not None

password = "@u2_>mypassw#ord123!*-"

if is_valid_password(password):
    print("Valid password")
else:
    print("Invalid password")

The following regex pattern should work以下正则表达式模式应该有效

r"^.*[A-Za-z]+.*\d+.*$|^.*\d+.*[A-Za-z]+.*$"

Explanation:解释:

  • ^.*[A-Za-z]+.*\d+.*$ : finds passwords with letters before numbers ^.*[A-Za-z]+.*\d+.*$ :查找字母在数字之前的密码
  • ^.*\d+.*[A-Za-z]+.*$ : finds passwords with numbers before letters ^.*\d+.*[A-Za-z]+.*$ :查找字母前有数字的密码
  • | : use OR to find one sequence OR the other :使用 OR 找到一个序列 OR 另一个
  • .* : used to find 0 or more characters of any type at this position .* :用于在此位置查找 0 个或多个任意类型的字符
  • [A-Za-z]+ : used to find 1 or more letters at this position [A-Za-z]+ :用于在此位置查找 1 个或多个字母
  • \d+ : used to find 1 or more numbers at this position \d+ :用于在此位置查找 1 个或多个数字
  • ^ and $ : start and end of line respectively ^$ :分别是行的开始结束

Regex101 Demo Regex101 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM