day16正则表达式作业

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

import re
from re import fullmatch, search, findall, I

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. 密码匹配

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

​ 2.必须以字母开头

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

password = input('请输入密码:')
result = fullmatch(r'(?i)[a-z][^!@#¥%^&*]{5,11}', password)
if result:
    print(f'"{password}"合法')
elseprint(f'"{password}"不合法')

  1. 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
            	elseprint('ip地址不合法')
            	break
    	else:
        	print('ip地址合法')
    except ValueError:
        print('ip地址不合法')

  1. 提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和
例如:“-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))

  1. 验证输入内容只能是汉字

    re_str = r'[\u4e00-\u9fa5]+'
    print(fullmatch(re_str, '你好啊'))
    
  2. 匹配整数或者小数(包括正数和负数)

    result = fullmatch(r'[-+]?(0|[1-9]\d*|0\.\d+|[1-9]\d*\.\d+)', '-41.265')
    print(result)
    
    
  3. 使用正则表达式获取字符串中所有的日期信息 匹配年月日日期 格式: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'))
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值