Day17 作业

  1. 判断IP地址

    # 0-199 200-255
    # re_str = r'(1?[0-9]?[0-9]|2[0-5]{2})\.(1?[0-9]?[0-9]|2[0-5]{2})' \
    #          r'\.(1?[0-9]?[0-9]|2[0-5]{2})\.(1?[0-9]?[0-9]|2[0-5]{2})'
    
    re_str = r'((1?[0-9]?[0-9]|2[0-5]{2})\.){3}(1?[0-9]?[0-9]|2[0-5]{2})'
    
    result1 = re.fullmatch(re_str, '255.189.10.37')
    result2 = re.fullmatch(re_str, '256.189.89.9')
    print(result1)
    print(result2)
    
    运行结果:
    <_sre.SRE_Match object; span=(0, 13), match='255.189.10.37'>
    None
    
  2. 计算一个字符串中所有数字的和

    re_str = r'\d+\.\d+|\d+'
    str1 = 'hello90abc 78sjh12.5'
    result1 = re.findall(re_str, str1)
    print(result1)
    sum1 = 0
    for num in result1:
        sum1 += float(num)
    print(sum1)
    
    运行结果:
    ['90', '78', '12.5']
    180.5
    
  3. 验证输入的内容只能是汉字

    re_str = r'[\u4e00-\u9fff]*'
    result1 = re.fullmatch(re_str, '我爱你')
    result2 = re.fullmatch(re_str, '我爱你1')
    print(result1)
    print(result2)
    
    运行结果:
    <_sre.SRE_Match object; span=(0, 3), match='我爱你'>
    None
    
  4. 验证电话号码

    re_str = r'1\d{10}'
    result1 = re.fullmatch(re_str, '18323161310')
    print(result1)
    
    运行结果:
    <_sre.SRE_Match object; span=(0, 11), match='18323161310'>
    
  5. 简单的身份证号码验证

    # 没有考虑闰年以及平年时以及每个月对应的天数
    re_str = r'[1-8]{2}[0-9]{4}[1-2][8-9][1-9]{2}(0[1-9]|1[0-2])([0-2][1-9]|3[0-1])[0-9]{3}([0-9]|X|x)'
    result1 = re.fullmatch(re_str, '13048118970228211x')
    print(result1)
    
    运行结果:
    <_sre.SRE_Match object; span=(0, 18), match='13048118970228211x'>
    

你可能感兴趣的:(Day17 作业)