利用正则表达式完成下面的操作:
1.用户名匹配
要求: 1.用户名只能包含数字 字母 下划线
2.不能以数字开头
3.⻓度在 6 到 16 位范围内
user_name = input('请输入用户名:')
result = fullmatch(r'[a-zA-Z_][\da-zA-Z_]{5,15}', user_name)
# result = fullmatch(r'(?i)[a-z][\da-zA-Z_]{5,15}', user_name)
if result:
print(f'"{user_name}"合法')
else:
print(f'"{user_name}"不合法')
- 密码匹配
要求: 1.不能包含!@#¥%^&*这些特殊符号
2.必须以字母开头
3.⻓度在 6 到 12 位范围内
password = input('请输入密码:')
result = fullmatch(r'(?i)[a-z][^!@#¥%^&*]{5,11}', password)
if result:
print(f'"{password}"合法')
else:
print(f'"{password}"不合法')
- ipv4 格式的 ip 地址匹配
提示: IP地址的范围是 0.0.0.0 - 255.255.255.255
# 方法一:正则
# 0-99合并的情况
r'([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])'
# 0-99没有合并的情况
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])'
print(fullmatch(re_str, '9.255.56.234'))
# 方法二:按字符串
ip = '255.255.255.255'
nums = ip.split('.')
if len(nums) != 4:
print('ip地址不合法!')
else:
try:
for x in nums:
if 0 <= int(x) <= 255:
if len(x) > 1 and x[0] == '0':
print('ip地址不合法')
break
else:
print('ip地址不合法')
break
else:
print('ip地址合法')
except ValueError:
print('ip地址不合法')
- 提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和
例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
# 方法一:
result = split(r'[^\d.-]', '-3.14good87nice19bye')
total = 0
str1 = ''
for i in result:
if i != '':
str1 += i
str1 += '+'
print(eval(str1[0:-1]))
# 方法二:
str1 = '-3.14good87nice19bye'
re_str = r'-?\d+\.?\d*'
result = findall(re_str, findall)
print(reduce(lambda x, y:x+float(y), result, 0))
-
验证输入内容只能是汉字
result = fullmatch(r'[\u4e00-\u9fa5]+', '士大夫立刻机') print(result)
-
匹配整数或者小数(包括正数和负数)
result = fullmatch(r'[-+]?(0|[1-9]\d*|0\.\d+|[1-9]\d*\.\d+)', '-41.265') print(result)
-
使用正则表达式获取字符串中所有的日期信息 匹配年月日日期 格式:2018-12-6
注意年的范围是1~9999, 月的范围是1~12, 日的范围是130或者131或者1~29(不考虑闰年)
re_str = '20181029' year = match(r'[1-9]\d{3}', re_str) month = fullmatch(r'\d*', re_str[len(year.group()):]) day = month.group()[2:] print(f'当前日期为:{year.group()}-{month.group()[0:2]}-{day}') # 年: # [1-9]\d*{0,3} # 月、日 # 1-30的正则:[1-9]|[12]\d|30 # 小月份:(0?[469]|11)-(0?[1-9]|[12]\d|30) # 大月份:(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]) # 二月:0?2-(0?[1-9]|[12]\d) re_str = r'[1-9]\d{0,3}-(((0?[469]|11)-(0?[1-9]|[12]\d|30))|((0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(0?2-(0?[1-9]|[12]\d)))' print(fullmatch(re_str, '1998-2-29'))