day15正则表达式作业

利用正则表达式完成下面的操作:

1.用户名匹配

​ 要求: 1.用户名只能包含数字 字母 下划线

​ 2.不能以数字开头

​ 3.长度在 6 到 16 位范围内

from re import fullmatch
re_str = r'^[a-zA-Z_][a-zA-Z\d_]{5,15}'
username = fullmatch(re_str, 'a12345')
print(username)

2.密码匹配

​ 要求: 1.不能包含!@#¥%^&*这些特殊符号

​ 2.必须以字母开头

​ 3.长度在 6 到 12 位范围内

from re import fullmatch
re_str = r'^[a-zA-Z][^!@#¥%^&*]{5,11}'
code = fullmatch(re_str, 'a12345')
print(code)

3, ipv4 格式的 ip 地址匹配
提示: IP地址的范围是 0.0.0.0 - 255.255.255.255

from re import fullmatch
re_str = r'((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]'
ip = fullmatch(re_str, '1.1.1.1')
print(ip)

4,提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和

例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
from re import findall
re_str2 = r'(-?\d+(\.\d+)?)'
a = dict(findall(re_str2, '-3.14good87nice19bye'))
b = list(a.keys())
total = sum(float(x) for x in b)
print(total)

5, 验证输入内容只能是汉字

from re import fullmatch
re_str = r'[\u4e00-\u9fa5]'
content = fullmatch(re_str, '你')
print(content)

6.匹配整数或者小数(包括正数和负数)

from re import fullmatch
re_str = r'-?\d+(\.\d+)?'
num = fullmatch(re_str, '-1')
print(num)

猜你喜欢

转载自blog.csdn.net/AncenaJune/article/details/113954883