1.用户名匹配
要求: 1.用户名只能包含数字 字母 下划线
2.不能以数字开头
3.⻓度在 6 到 16 位范围内
import re user_name = re.compile(r'[a-zA-Z_][\da-zA-Z_]{5,15}') print(user_name.fullmatch('dfewrerdf_')) 密码匹配 要求: 1.不能包含!@#¥%^&*这些特殊符号
2.必须以字母开头
3.⻓度在 6 到 12 位范围内
pass_words = re.compile(r'[a-zA-Z]([^!@#¥%^&*]){5,11}') print(pass_words.fullmatch('python')) ipv4 格式的 ip 地址匹配 提示: IP地址的范围是 0.0.0.0 - 255.255.255.255 ipv4 = re.compile(r'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.?){4}') print(ipv4.fullmatch('255.255.55.0')) 提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和 例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86 nums = re.compile(r'-?\d+(\.\d+)?') result = nums.finditer('-3.14good87nice19bye') list1 = list(result) sum1 = 0 for i in list1: sum1 += eval(i.group()) print(sum1)验证输入内容只能是汉字
chinese = re.compile(r'[\u4e00-\u9fa5]+') print(chinese.fullmatch('淦'))匹配整数或者小数(包括正数和负数)
nums2 = re.compile(r'(-?\d+(\.\d+)?)') print(nums2.fullmatch('-123.2321'))使用正则表达式获取字符串中所有的日期信息 匹配年月日日期 格式:2018-12-6
注意年的范围是1~9999, 月的范围是1~12, 日的范围是130或者131或者1~29(不考虑闰年)
date = re.compile( r'([1-9][0-9]{0,3})-((([13578]|10|12)-(31|30|[1-2][0-9]|[1-9]))|(([469]|11)-(30|[1-2][0-9]|[1-9]))|(2-([1-2][0-9]|[1-9])))') result = date.finditer('0-2-23dfjdlkf1921-8-30ljd23455-4-31') list2 = list(result) for i in list2: print(i.group())替换字符串中的不良内容:将输入的内容中的不良内容全部替换成*(参考王者荣耀聊天要求)
chat = re.compile(r'(傻逼|sb|SB|艹)') result = chat.sub('*', 'sdfsdfhksb') print(result)