将密码与 Python 正则表达式匹配 [英] Match password with Python regex

查看:86
本文介绍了将密码与 Python 正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的密码要求是:

  • 至少 10 个符号

  • 至少一位数

  • 至少一个大写字母

  • 至少一个小写字母

  • 只有字母或数字

所以我想使用 re 模块来检查我的字符串输入:re.search(pattern, string).

我在这里的模式应该是什么?

解决方案

是的,你可以通过正则表达式做到这一点.

^(?=.*?\d)(?=.*?[A-Z])(?=.*?[a-z])[A-Za-z\d]{10,}$

演示

<预><代码>>>>进口重新>>>m = re.compile(r'^(?=.*?\d)(?=.*?[AZ])(?=.*?[az])[A-Za-z\d]{10,}$')>>>m.match('43543fooR')>>>m.match('43543fooRy')<_sre.SRE_Match 对象;span=(0, 10), match='43543fooRy'>>>>m.match('foobar7678A')<_sre.SRE_Match 对象;span=(0, 11), match='foobar7678A'>>>>m.match('foobar76(')>>>m.match('fokhjf7645464644sresrtf')>>>m.match('fokhjf764546M4644sresrtf')<_sre.SRE_Match 对象;span=(0, 24), match='fokhjf764546M4644sresrtf'>>>>

  • (?=.*?\d) 检查至少一位数字
  • (?=.*?[A-Z]) 至少一个大写.
  • (?=.*?[a-z]) 至少一个小写.
  • [A-Za-z\d]{10,} 匹配大写或小写或数字字符 10 次或更多次.这可确保匹配项必须至少包含 10 个字符.

The requirements for my password are:

  • at least 10 symbols

  • at least one digit

  • at least one uppercase letter

  • at least one lowercase letter

  • only letters or digits

So I want to use the re module to check my string input: re.search(pattern, string).

What should be my pattern here?

解决方案

Yep, you could do this through regex.

^(?=.*?\d)(?=.*?[A-Z])(?=.*?[a-z])[A-Za-z\d]{10,}$

DEMO

>>> import re
>>> m = re.compile(r'^(?=.*?\d)(?=.*?[A-Z])(?=.*?[a-z])[A-Za-z\d]{10,}$')
>>> m.match('43543fooR')
>>> m.match('43543fooRy')
<_sre.SRE_Match object; span=(0, 10), match='43543fooRy'>
>>> m.match('foobar7678A')
<_sre.SRE_Match object; span=(0, 11), match='foobar7678A'>
>>> m.match('foobar76(')
>>> m.match('fokhjf7645464644sresrtf')
>>> m.match('fokhjf764546M4644sresrtf')
<_sre.SRE_Match object; span=(0, 24), match='fokhjf764546M4644sresrtf'>
>>> 

  • (?=.*?\d) Checks for atleast one digit
  • (?=.*?[A-Z]) Atleast one uppercsae.
  • (?=.*?[a-z]) Atleast one lowercase.
  • [A-Za-z\d]{10,} Matches uppercase or lowercase or digit characters 10 or more times. This ensures that the match must have atleast 10 characters.

这篇关于将密码与 Python 正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆