from re import *
1. 寫一個正則表達式判斷一個字符串是否是ip地址
規(guī)則:一個ip地址由4個數(shù)字組成打颤,每個數(shù)字之間用.連接。每個數(shù)字的大小是0-255
255.189.10.37 正確
256.189.89.9 錯誤
result = fullmatch(r'((1?\d?\d|2[0-4]\d|25[0-5])\.){3}(1?\d?\d|2[0-4]\d|25[0-5])', '254.189.89.9')
if result:
print('正確')
else:
print('錯誤')
2. 計算一個字符串中所有的數(shù)字的和
例如:字符串是:‘hello90abc 78sjh12.5’ 結(jié)果是90+78+12.5 = 180.5
str1 = '.10hello90abc -78sjh12.5da8ad'
result = findall(r'-?\d+.?\d+|\d', str1)
sum_result: float = 0
for item in result:
sum_result += float(item)
3. 驗證輸入的內(nèi)容只能是漢字
str_unknow = input('隨便輸入:')
if fullmatch(r'[\u4e00-\u9fa5]+', str_unknow):
print('純漢字')
else:
print('歪果仁')
4. 電話號碼的驗證
call = input('輸入電話號碼:')
if fullmatch(r'1[3-9]\d{9}', call):
print('yes')
else:
print('no')