- 写一个正则表达式判断一个字符串是否是ip地址
规则:一个ip地址由4个数字组成,每个数字之间用.连接。每个数字的大小是0-255
255.189.10.37 正确
256.189.89.9 错误
import re
re_str = r"((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d])\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d])"
print(re.fullmatch(re_str,"255.189.10.37")!=None) # Ture
print(re.fullmatch(re_str,"256.189.10.37")!=None) # False
- 计算一个字符串中所有的数字的和
例如:字符串是:‘hello90abc 78sjh12.5’ 结果是90+78+12.5 = 180.5
import re
re_str = r"\d+\.\d+|[1-9]\d*|\d"
l = re.findall(re_str,"he109llo90abc 78sjh12.5")
sum11 = 0
for item in l:
num = float(item)
sum1 += num
print(sum1)
- 验证输入的内容只能是汉字
import re
re_str = r"[一-龥]+"
print(re.fullmatch(re_str,"鸟瞰独食难肥了看电视呢发"))
- 电话号码的验证
import re
re_str = r"1[358]\d{9}|0[1-9]\d{1,2}-\d{7,8}|00[1-9]\d{1,2}-\d{7,8}"
print(re.fullmatch(re_str,"00190-75543211"))
- 简单的身份证号的验证
import re
class IdCard:
def __init__(self, card_num=""):
self.card_num = card_num
def validation(self):
re_str = r"\d{18}|\d{17}X"
coefficient = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
result = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]
if re.fullmatch(re_str, self.card_num) != None:
index = 0
sum = 0
for s in self.card_num[:-1]:
sum += int(s) * coefficient[index]
index += 1
if result[sum % 11] == self.card_num[-1]:
return True
else:
return False
else:
return False
idcard = IdCard("5113241******00018")
print(idcard.validation())
二、不定项选择题
能够完全匹配字符串“(010)-62661617”和字符串“01062661617”的正则表达式包括(AB )
A. “(?\d{3})?-?\d{8}”
B. “[0-9()-]+”
C. “[0-9(-)]\d”
D. “[(]?\d[)-]\d*”能够完全匹配字符串“c:\rapidminer\lib\plugs”的正则表达式包括(BCD )
A. “c:\rapidminer\lib\plugs”
B. “c:\rapidminer\lib\plugs”
C. “(?i)C:\RapidMiner\Lib\Plugs” ?i:将后面的内容的大写变成小写
D. “(?s)C:\RapidMiner\Lib\Plugs” ?s:单行匹配能够完全匹配字符串“back”和“back-end”的正则表达式包括(ABD )
A. “\w{4}-\w{3}|\w{4}” match->back,back-end fullmatch-> back,back-end
B. “\w{4}|\w{4}-\w{3}” match-> back, back fullmatch-> back,back-end
C. “\S+-\S+|\S+”
D. “\w\b-\b\w|\w*”能够完全匹配字符串“go go”和“kitty kitty”,但不能完全匹配“go kitty”的正则表达式包括(AD )
:\1就是重复前面第一个()/组合里面的内容
:\2就是重复前面第二个()/组合里面的内容
A. “\b(\w+)\b\s+\1\b”
B. “\w{2,5}\s*\1”
C. “(\S+) \s+\1”
D. “(\S{2,5})\s{1,}\1”能够在字符串中匹配“aab”,而不能匹配“aaab”和“aaaab”的正则表达式包括(BC )
A. “a*?b”
B. “a{,2}b”
C. “aa??b”
D. “aaa??b”