使用Python中的单个正则表达式在输入字符串中搜索整数和字符的出现

时间:2011-12-05 10:32:42

标签: python regex

我有一个输入字符串,只有在包含:

时才被视为有效
  • [a-z]
  • 中至少有一个字符
  • [0-9]和
  • 中至少有一个整数
  • [A-Z]
  • 中至少有一个字符

对上述任何一种的发生顺序没有限制。如何编写一个验证输入字符串的正则表达式?

2 个答案:

答案 0 :(得分:5)

试试这个

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$

here online on 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

答案 1 :(得分:5)

你需要正则表达吗?

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):

或@ YuvalAdam改进的改进版本:

if all(any(c in x for c in t) for x in (string.uppercase, string.lowercase, string.digits)):