Skip to main content
 首页 » 编程设计

用于密码验证的python正则表达式

2025年05月04日23wayfarer

我有以下要求使用以下上下文验证密码

  • 至少一位数
  • 至少一个大写字母
  • 至少一个小写字母
  • 至少一个特殊字符[$@#]

下面的程序是做部分匹配而不是完整的正则表达式

#!/usr/sfw/bin/python 
import re 
password = raw_input("Enter string to test: ") 
if re.match(r'[A-Za-z0-9@#$]{6,12}', password): 
    print "match" 
else: 
    print "Not Match" 

正在使用中:

localhost@user1$ ./pass.py 
Enter string to test: abcdabcd 
match 

它正在评估错误的输出。任何人都可以在这里建议我应该使用 re.search 吗?

请您参考如下方法:

这是至少一位数字、一个大写字母、至少一个小写字母、至少一个特殊字符的正则表达式

import re 
password = input("Enter string to test: ") 
# Add any special characters as your wish I used only #@$ 
if re.match(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$])[\w\d@#$]{6,12}$", password): 
    print ("match") 
else: 
    print ("Not Match") 

希望这对你有帮助...