我在为以下语句编写正则表达式模式时遇到问题。我认为我的电子邮件模式有问题。
电子邮件:
google.com
或 (nothing or any characters).go
$
密码:
!@#$%^
email_pattern = re.compile(r'^((?=.*\$)((?=.*[0-9]){3,})(?=.*[a-z]*))(\@)((google\.com)|([a-z0-9\!\@\#\%\^\&]*\.go))$')
pass_pattern = re.compile(r'((?=.*(\!|\@|\#|\$|\%|\^))(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])(?=.*[a-zA-z0-9!@#$%^]*)){8,}')
我认为没有必要使用这种正则表达式。它们很可怕、难以理解并且难以定制。如果您需要验证电子邮件和密码,那么为什么不将其分解为几个步骤呢?是的,可能会有更多代码,但与其进一步交互将变得更容易。如有必要,您可以删除其中一项检查或添加一项新检查,而无需触及其他检查。阅读一些有关“分而治之”原则的内容。
这是针对您的问题的易于定制和可读的解决方案之一:
import re
def email_is_valid(email:str) -> bool:
''' Returns True if email is valid and False if it's not
'''
conditions = [
# Checking for correct ending and forbidden characters
re.fullmatch(r'[a-z0-9$]{1,}((@google.com)|(\.go))$', email),
# Checking for at least three digits
re.search(r'(?=(?:.*\d){3,})', email),
# Checking for only one '$'
re.search(r'(?=(?:.*\$){1})', email),
]
for condition in conditions:
if not condition:
return False
return True
def password_is_valid(password:str) -> bool:
''' Returns True if password is valid and False if it's not
'''
conditions = [
# Checking the length and presence of forbidden characters
re.fullmatch(r'[A-Za-z0-9!@#$%^]{8,}', password),
# Looking for at least one of these characters !@#$%^
re.search(r'[!@#$%^]{1,}', password),
# Looking for at least one Uppercase letter
re.search(r'[A-Z]{1,}', password),
]
for condition in conditions:
if not condition:
return False
return True
以下是这些函数的使用方式。易于阅读。
import email_is_valid, password_id_valid
if email_is_valid(your_email):
...
if password_id_valid(your_password):
...