利用正则表达式完成下面的操作:
1.用户名匹配
要求: 1.用户名只能包含数字 字母 下划线
2.不能以数字开头
3.⻓度在 6 到 16 位范围内
from re import fullmatch
user = r'[a-zA-Z_][a-zA-Z_\d]{5,15}'
result = fullmatch(user, 'aaasd12563')
print(result)
- 密码匹配
要求: 1.不能包含!@#¥%^&*这些特殊符号
2.必须以字母开头
3.⻓度在 6 到 12 位范围内
from re import fullmatch
re_str = r'[a-zA-Z][^!@#¥%^&*]{5,11}'
result = fullmatch(re_str, 'asd6548')
print(result)
- ipv4 格式的 ip 地址匹配
提示: IP地址的范围是 0.0.0.0 - 255.255.255.255
from re import fullmatch
re_str = r'([0-9]\.?|[1-9]\d\.?|1\d\d\.?|2[0-4]\d\.?|25[0-5]\.?){4}'
result = fullmatch(re_str, '5.20.13.14')
print(result)
- 提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和
例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
from re import fullmatch, findall
re_str = '-?\d+\.?\d+|-?\d+'
list1 = findall(re_str, '-3.14good87nice19bye')
print(sum(float(x) for x in list1))
-
验证输入内容只能是汉字
from re import fullmatch, findall re_str = '[\u4e00-\u9fa5]+' result = fullmatch(re_str, '风华正茂翁忠斌') print(result)
-
匹配整数或者小数(包括正数和负数)
from re import fullmatch, findall re_str = '\d+\.?\d+' result = fullmatch(re_str, '198654') print(result)
-
使用正则表达式获取字符串中所有的日期信息 匹配年月日日期 格式:2018-12-6
注意年的范围是1~9999, 月的范围是1~12, 日的范围是130或者131或者1~29(不考虑闰年)
from re import fullmatch re_str = r'[0-9]{1,4}\-[1-9]\-[1-9]|[0-9]{1,4}\-1[12]\-[1-9]|[0-9]{1,4}\-[1-9]\-2[1-9]|[0-9]{1,4}\-1[12]\-2[1-9]|[0-9]{1,4}\-[1-9]\-3[10]|[0-9]{1,4}\-1[12]\-3[10]' result = fullmatch(re_str, '2018-12-6') print(result)
-
替换字符串中的不良内容:将输入的内容中的不良内容全部替换成*(参考王者荣耀聊天要求)
from re import fullmatch, findall, sub fuck = 'nm' print(sub(fuck, '阿姨', 'nm今天喊你吃饭了吗?'))