考虑以下正则表达式,它检查密码强度。它具有开始和结束字符串锚点,以确保它匹配整个字符串。
pattern = re.compile(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[$@$!%*#?&.])[A-Za-z\d$@$!%*#?&.]{8,}$')
while True:
user_pass = input('Enter a secure password: ')
if re.fullmatch(pattern, user_pass):
print('Successfully changed password')
break
else:
print('Not secure enough. Ensure pass is 8 characters long with at least one upper and lowercase letter, number,'
' and special character.')
Run Code Online (Sandbox Code Playgroud)
我注意到 Python 3.5 有一个 re.fullmatch() 似乎做同样的事情,但没有字符串锚点:
pattern = re.compile(r'(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[$@$!%*#?&.])[A-Za-z\d$@$!%*#?&.]{8,}')
while True:
user_pass = input('Enter a secure password: ')
if re.fullmatch(pattern, user_pass):
print('Successfully changed password')
break
else:
print('Not secure enough. Ensure pass is 8 characters long with at least one upper and lowercase letter, number,'
' and special character.')
Run Code Online (Sandbox Code Playgroud)
这是 fullmatch 的预期目的吗?是否有任何情况会导致意外问题?
该fullmatch()函数和regex.fullmatch()方法在Python 3.4是新的。
变更日志对此非常明确:
这提供了一种明确匹配目标的方法,从而避免了一类微妙的错误,即在代码更改或向现有正则表达式添加替代项期间 $ 字符丢失的情况。
因此,您使用它的方式确实是此功能的预期目的。它不能导致意想不到的问题,^而$只是谨慎内部添加。