如何在 Python 中测试正则表达式密码?

2023-09-28Python开发问题
5

本文介绍了如何在 Python 中测试正则表达式密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 Python 中使用正则表达式,我如何验证用户的密码是:

Using a regex in Python, how can I verify that a user's password is:

  • 至少 8 个字符
  • 必须限于,但不具体要求:
    • 大写字母:A-Z
    • 小写字母:a-z
    • 数字:0-9
    • 任何特殊字符:@#$%^&+=

    注意,所有字母/数字/特殊字符都是可选的.我只想验证密码长度是否至少为 8 个字符,并且仅限于字母/数字/特殊字符.如果他们愿意,用户可以选择更强/更弱的密码.到目前为止,我所拥有的是:

    Note, all the letter/number/special chars are optional. I only want to verify that the password is at least 8 chars in length and is restricted to a letter/number/special char. It's up to the user to pick a stronger / weaker password if they so choose. So far what I have is:

    import re
    pattern = "^.*(?=.{8,})(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"
    password = raw_input("Enter string to test: ")
    result = re.findall(pattern, password)
    if (result):
        print "Valid password"
    else:
        print "Password not valid"
    

    推荐答案

    import re
    password = raw_input("Enter string to test: ")
    if re.fullmatch(r'[A-Za-z0-9@#$%^&+=]{8,}', password):
        # match
    else:
        # no match
    

    {8,} 表示至少 8 个"..fullmatch 函数要求整个字符串匹配整个正则表达式,而不仅仅是一部分.

    The {8,} means "at least 8". The .fullmatch function requires the entire string to match the entire regex, not just a portion.

    这篇关于如何在 Python 中测试正则表达式密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

    The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10