饭前甜点1:随机生成一个包含正负整数以及正负浮点数的列表
def value_type(s=''):
li = [random.randint(-10,10) for _ in range(10)] + [random.uniform(-10,10) for _ in range(10)]
for i in li:
s += str(i) + ' '
return s
饭前甜点2:随机密码 包含①:8到10位数 ②:字母区分大小写且最少有一个,最多不能超过字符串的长度 ③全是数字提醒
def producePassword():
li = [8,9,10]
length = random.choice(li)
numlenth = random.choice(list(range(0,length-1)))
wordlenth = length - numlenth
word_list = []
for i in range(wordlenth):
word_limit = random.randint(*random.choice([(97,122),(65,90)]))
word_list.append(chr(word_limit))
numlist = [chr(random.randint(48,57)) for _ in range(numlenth)]
password_list = numlist + word_list
random.shuffle(password_list)
s = ''
for i in password_list:
s += i
return s
有了两道甜点,我们可以进餐了
副餐(初阶例题):
#经典案例1:求非负整数 /数字中间不能有小数点,不能一负号开头
a = re.findall(r'^\d | \d ',s)
#经典案例2:非正整数 零既不是正数也不是负数
b = re.findall(r'-[1-9]+',s)
#经典案例3:非负浮点数
c = re.findall(r'\d+\.\d+ ',s)
#经典案例4:非正浮点数
d = re.findall(r'-\d+\.\d+ ',s)
有了以上案例,我相信你能发明创造出更多的初阶例题,有什么bug请留言,第一时间修改
主餐(难):第二道甜品派上用场了
randpaw = producePassword() #生成的随机密码
#案例1:匹配8-10位的用户密码
def judge_password(s):
moud1 = re.compile(r'^[a-zA-Z0-9]{8,10}$')
moud2 = re.compile(r'^[0-9]{8,10}$')
while True:
possword_str1 = re.search(moud1,s)
possword_str2 = re.search(moud2,s)
try:
if possword_str1:
# logging.debug(possword_str1.group())
print('输入密码成功>>>',end =' ')
if possword_str2:
print('您输入的密码风险值较高,请注意使用安全')
return possword_str1.group()
else:
raise ValueError
except:
print('您输入的密码不符合规范,请输入8-10位的数字与字母的组合')
这道例题当然,由于是按规则生成的,所以无论怎么匹配都不会抛出ValueError,但是你可以修改函数从而达到接受用户输入并且匹配的目的,暂且就说这么多
#案例2:验证输入的只能是汉字
def charaJudge():
s = input('请输入:')
result = re.search(r'^[\u2E80-\u9FFF]+$',s)
if result:
return result
else:
print('输入不符合要求')
不要问我明明很简单的问题,为什么非要装个滴来用一个简单的函数,因为我也不知道
#案例3:电子邮箱验证:
电子邮箱的规则或者说是模式:数字或者字母(r'^\w+[._-]?\w+')
s = 'fexn_3123@qq.cn' #
a = re.search(r'^[0-9a-z]+[._-]?[0-9a-z]+@[a-z]{2}\.(com|cn)$',s)
#案例4:url地址验证 http://cahivabviavbjkssbvcixgiv.com(cn)
s = 'https://www.baicacavdavadu.com'
a = re.search(r'^(http:|https:)/{2}w{3}\.[a-z0-9A-Z]+\.(com|cn)$',s)
#案例5:简单的身份证号码的验证
a = re.search(r'\d{17}(\d|X)$','123456789123456789')
#经典案例6:匹配ip地址,注意ip地址的每一个数都是从0-255,而且位数不一定都是三位
ip = '2.168.0.10'
a = re.search(r'^(?:(?:1\d\d\.)|(?:2[0-4]\d\.)|(?:25[0-5]\.)|(?:[1-9]\d\.)|(?:\d\.)){3}(?:(?:1\d\d)|(?:2[0-4]\d)|(?:25[0-5])|(?:[1-9]\d))|(?:\d)$',ip)
b = re.search(r'^(?:(?:[0,1]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[0,1]?\d?\d|2[0-4]\d|25[0-5])$',ip)
简单说一下思路:如果第一个数是1那么后边是任意的两位正整数,如果第一个数是2第二个数是那么第二个数只能是从0到4第三个数只能是0到5,如果第一个数是2第二个数是5那么第三个数只能是0到5,以此类推
个人认为这个是最绕的,最让人欲罢不能的
#经典案例7:匹配电话号码
phnum = '12345678901'
a = re.search(r'^1\d{10}$',phnum)
########终极版##########
#案例1:提取捕获html各个标签的内容
吃不下了暂时。。。。。。