gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:54 25 4
gpt4 key购买 nike

我有一个输入字符串,只有当它包含以下内容时才被认为是有效的:

  • 至少 [a-z] 中的一个字符
  • 至少一个[0-9]中的整数,以及
  • 至少一个 [A-Z] 中的字符

以上任何一项的出现顺序都没有限制。如何编写一个验证输入字符串的正则表达式?

最佳答案

试试这个

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

查看here online on Regexr

^$ 是将模式绑定(bind)到字符串开头和结尾的 anchor 。

(?=...) 是先行断言。他们检查 = 之后的模式是否在前面,但他们不匹配。因此,要匹配某些东西,还需要有一个真实的模式。这是末尾的 .*
.* 也会匹配空字符串,但是一旦其中一个前瞻失败,整个表达式就会失败。

对于那些关心可读性和可维护性的人,使用 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

关于python - 在 Python 中使用单个正则表达式在输入字符串中搜索出现的整数和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8383969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com