python - 正则表达式搜索以检查字符串中的多个条件

标签 python regex

我是使用正则表达式和 Python 的新手,为了获得一些练习,我认为我应该编写一个程序来模拟检查用户名和密码的条件。我想要的密码要求是:

# 1. have one or more special characters
# 2. have one or more lowercase letters
# 3. have one or more uppercase letters
# 4. have one or more numbers

但是我想出的变量...

req_characters = r"([@#$%&*-_/\.!])+([a-z])+([A-Z])+([0-9])+"

以及正则表达式搜索功能...

    elif not re.search(req_characters, string):
    print("Your password must contain at least one uppercase and one 
           lowercase letter, one number, and one special character.")

产生应该匹配的字符串,从而触发 if 语句。具体来说,如果我输入字符串

#This_is_stuff0123

我收到打印语句,因此正则表达式认为条件尚未满足。但是,如果我输入字符串

##azAZ01

它匹配,这告诉我正则表达式只会按顺序获取这些字符类/组。我尝试了各种带括号的分组均无济于事,然后尝试按以下方式使用“或”,得到相同的结果:

req_characters = r"([@#$%&*-_/\.!]|[a-z]|[A-Z]|[0-9]){6, 30}"

所以我想知道编辑当前正则表达式以实现此结果的简单解决方案是什么。

最佳答案

我不太确定,如果 this expression可能会匹配您的所有输入,但是它可能会帮助您设计一个表达式来执行此操作:

 ^(?=.+[@#$%&*-_\/\.!])(?=.+[a-z])(?=.+[A-Z])(?=.+[0-9])[A-Za-z0-9@#$%&*-_\/\.!]{6,30}$

enter image description here

代码:

import re

string = 'A08a^&0azA'
# string = 'A08a^&0azAadA08a^&0azAadA08a^&0azAad'
matches = re.search(r'^((?=.+[@#$%&*-_\/\.!])(?=.+[a-z])(?=.+[A-Z])(?=.+[0-9])[A-Za-z0-9@#$%&*-_\/\.!]{6,30})$', string)
if matches:
    print(matches.group(1)+ " is a match")
else: 
    print('Sorry! No matches! Something is not right! Call 911')

输出

A08a^&0azA is a match

图表

enter image description here

关于python - 正则表达式搜索以检查字符串中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55963504/

相关文章:

python - Django Admin,保存时调用函数

python - 使用 findall python 从推文中提取@mentions(给出不正确的结果)

javascript - Jquery如何获取特定字符串内容

python - 主函数中没有调用函数

python - 使用 Drive python API 在 Google 电子表格中设置 "publish to web"

python - 多索引第二级的时间片

python - 长时间运行的批处理在 Ubuntu 中过早终止

java - 按数字正则表达式分割字符串

用于检测 semver 字符串的 Java 正则表达式在没有限定符的情况下失败

java - Java 中的正则表达式,如果找到 "N","E","W","S"以外的任何字符,则返回 false