一、强口令检测:
写一个函数,它使用正则表达式,确定传入的口令字符串是强口令。强口令的定义是:长度不少于8个字符,同时包含大写和小写字符,至少有一位数字。你可能需要多个正则表达式来测试该字符串,以保证它的强度。
代码如下:
class ValueErro(Exception) : pass
class checkPWD:
'''
密码条件:必须要有大写字母、小写字母、数字,中间不能有空格。
'''
def __init__(self,cstr) :
self.cstr = cstr
def docheck(self,cstr):
cstr = cstr.strip()
cReturn = True
if len(self.cstr) < 8 :
raise ValueError('密码长度不足8位。')
cReturn = False
if cstr.find(' ') > 0 :
raise ValueError('密码中不能有空格。')
cReturn = False
import re
#查找数字
__num = re.compile(r'\d?') #有问号
g = __num.findall(cstr)
print(g)
if len(g) <= 0 :
raise ValueError('密码中必须要有数字!')
cReturn = False
#查找大写字母
__upp = re.compile(r'[ABCDEFGHIJKLMNOPQRSTUVWXYZ]?') #有问号
g = __upp.findall(cstr)
print(g)
if len(g) <= 0 :
raise ValueError('密码中必须要有大写字母!')
cReturn = False
#查找小写字母
__low = re.compile(r'[abcdefghijklmnopqrstuvwxyz]?') #有问号
g = __low.findall(cstr)
print(g)
if len(g) <= 0 :
raise ValueError('密码中必须要有小写字母!')
cReturn = False
return cReturn
pwd = 'abcde888Df'
p = checkPWD(pwd) # 如果不带pwd,会报错:需要cstr参数
print(p.docheck(pwd)) #输出:True
输出:
[‘’, ‘’, ‘’, ‘’, ‘’, ‘8’, ‘8’, ‘8’, ‘’, ‘’, ‘’]
[‘’, ‘’, ‘’, ‘’, ‘’, ‘’, ‘’, ‘’, ‘D’, ‘’, ‘’]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘’, ‘’, ‘’, ‘’, ‘f’, ‘’]
True
注意下一段代码与上一段代码的区别:
class ValueErro(Exception) : pass
class checkPWD:
'''
密码条件:必须要有大写字母、小写字母、数字,中间不能有空格。
'''
def __init__(self,cstr) :
self.cstr = cstr
def docheck(self,cstr):
cstr = cstr.strip()
cReturn = True
if len(self.cstr) < 8 :
raise ValueError('密码长度不足8位。')
cReturn = False
if cstr.find(' ') > 0 :
raise ValueError('密码中不能有空格。')
cReturn = False
import re
#查找数字
__num = re.compile(r'\d') #不带问号
g = __num.findall(cstr)
print(g)
if len(g) <= 0 :
raise ValueError('密码中必须要有数字!')
cReturn = False
#查找大写字母
__upp = re.compile(r'[ABCDEFGHIJKLMNOPQRSTUVWXYZ]') #不带问号
g = __upp.findall(cstr)
print(g)
if len(g) <= 0 :
raise ValueError('密码中必须要有大写字母!')
cReturn = False
#查找小写字母
__low = re.compile(r'[abcdefghijklmnopqrstuvwxyz]') #不带问号
g = __low.findall(cstr)
print(g)
if len(g) <= 0 :
raise ValueError('密码中必须要有小写字母!')
cReturn = False
return cReturn
pwd = 'abcde888Df'
p = checkPWD(pwd) # 如果不带pwd,会报错:需要cstr参数
print(p.docheck(pwd)) #输出:True
输出:
[‘8’, ‘8’, ‘8’]
[‘D’]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
True
二、strip()的正则表达式版本
写一个函数,它接受一个字符串,做的事情和strip()字符串方法一样。如果只传入了要去除的字符串,没有其他参数,那么就从该字符串首尾去除空白字符。否则,函数第二个参数指定的字符将从该字符串中去除。
代码如下:
def test(cstr,cword):
import re
while True :
mo = re.search('^ ', cstr) #从头找空格
if mo != None : #如果mo为None,则表示没有匹配的字符串
p = mo.group()
if len(p) > 0 :
cstr = cstr[1:] #从第2位向右截取字符串
print(cstr)
continue
else :
break
while True :
mo = re.search(' $', cstr) #从尾找空格
if mo != None : #如果mo为None,则表示没有匹配的字符串
p = mo.group()
if len(p) > 0 :
cstr = cstr[:len(cstr)-1]
print(cstr)
continue
else :
break
if cword != None :
while True :
cplace = cstr.find(cword)
if cplace == -1 :
break
else :
cstr = cstr[:cplace] + cstr[cplace+1:]
continue
return cstr
print(test(' abc-123 ','-'))
输出:
abc123