我有一个输入字符串,只有在包含以下内容时才被视为有效:
对上述任何一种的出现顺序没有限制.如何编写一个验证输入字符串的正则表达式?
试试这个
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$
Run Code Online (Sandbox Code Playgroud)
看到它在网上的Regexr
的^和$是其结合模式的开始和字符串的结尾锚.
该(?=...)是向前断言.他们检查后面的模式=是否提前但是它们不匹配.所以为了匹配某些东西,也需要一个真实的模式.这是.*最后的结果.
在.*将空字符串也匹配,但只要向前看符号之一失败,完整的表达式将失败.
对于那些担心可读性和可维护性的人,使用re.X修饰符来允许漂亮和注释的正则表达式:
reg = re.compile(r'''
^ # Match the start of the string
(?=.*[a-z]) # Check if there is a lowercase letter in the string
(?=.*[A-Z]) # Check if there is a uppercase letter in the string
(?=.*[0-9]) # Check if there is a digit in the string
.* # Match the string
$ # Match the end of the string
'''
, re.X) # eXtented option whitespace is not part of he pattern for better readability
Run Code Online (Sandbox Code Playgroud)
你需要正则表达吗?
import string
if any(c in string.uppercase for c in t) and any(c in string.lowercase for c in t) and any(c in string.digits for c in t):
Run Code Online (Sandbox Code Playgroud)
或@ YuvalAdam改进的改进版本:
if all(any(c in x for c in t) for x in (string.uppercase, string.lowercase, string.digits)):
Run Code Online (Sandbox Code Playgroud)