大写、小写和数字的正则表达式



我的任务是验证一个必须包含至少一个小写字母和大写字母以及至少一个数字的字符串。我不需要检查这个字符串的长度

我想做这样的事情:

from re import match

regexp = "^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])"
string_to_validate = input("Write string with uppercase/lowercase characters and numbers.")
if not match(regexp, string_to_validate):
raive ValueError("You should use uppercase and lowercase characters with numbers in your string")

但是在我看来,对于这个目的,似乎有一个表达式比那个要好得多。老实说,我甚至不知道表达式开头的符号"^"是干什么用的。

将需求分解为单独的正则表达式更易于维护和阅读,并使用re.search:

import re
strs = ['Bb2', 'Bb', 'b2', 'B2']
for s in strs:
if not (re.search(r'[A-Z]', s)
and re.search(r'[a-z]', s)
and re.search(r'd', s)):
print(f'Input "{s}" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.')
else:
print(f'Input "{s}" is OK')
# Input "Bb2" is OK
# Input "Bb" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "b2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "B2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.

最新更新