day17homework

写一个正则表达式判断一个字符串是否是ip地址

规则:一个ip地址由4个数字组成,每个数字之间用.连接。每个数字的大小是0-255

255.189.10.37 正确

256.189.89.9 错误


import re
from re import *

def func():
    while True:
        ip1 = input('请输入ip地址:')

        re_str = r'((([1-9][0-9])|[0-9]|([1][0-9][0-9])|([2][0-5][0-5]))\.){3}(([1-9][0-9])|[0-9]|([1][0-9][0-9])|([0-2][0-5][0-5]))'
        result = re.fullmatch(re_str,str(ip1))
        if result:
            print('正确')
            break
        else:
            print('不对')

func()

计算一个字符串中所有的数字的和

例如:字符串是:‘hello90abc 78sjh12.5’ 结果是90+78+12.5 = 180.5


def func():
    while True:
        ip1 = input('请输入字符串:')
        num1 = 0
        print(findall(r'\d+\.?\d+', ip1))

        for str1 in findall(r'\d+\.?\d+', ip1):
            num1 += float(str1)
        print(num1)

func()

验证输入的内容只能是汉字

def func():
    while True:
        ip1 = input('请输入字符串:')
        re_str = r'[\u4e00-\u9fa5]+'
        result = re.fullmatch(re_str, ip1)
        if result:
            print('正确')
            break
        else:
            print('不对')

func()

电话号码的验证

def func():
    while True:
        ip1 = input('请输入字符串:')
        re_str = r'1[0-9]{10}'
        result = re.fullmatch(re_str, ip1)
        if result:
            print('正确')
            break
        else:
            print('不对')

func()

你可能感兴趣的:(day17homework)