import re
from re import fullmatch,search
- 写一个正则表达式判断一个字符串是否是ip地址
规则:一个ip地址由4个数字组成,每个数字之间用.连接。每个数字的大小是0-255
255.189.10.37 正确
256.189.89.9 错误
写一个正则表达式,用来判断一个字符是否是IP地址
result = 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)'
ip = re.fullmatch(result, '255.78.78.10')
if ip:
print('是IP地址')
else:
print('不是IP地址')
- 计算一个字符串中所有的数字的和
例如:字符串是:‘hello90abc 78sjh12.5’ 结果是90+78+12.5 = 180.5
re_str = r'[+-]?\d+\.\d+|[+-]?\d+'
str1 = 'hello90abc 78sjh12.5'
str2 = re.search(re_str, str1)
count = 0
while str2:
count += float(str2.group())
end = str2.end()
str1 = str1[end:]
str2 = re.search(re_str, str1)
print(count)
- 验证输入的内容只能是汉字
#re_str = r'[^A-Za-z\s\s]'
#result = fullmatch(re_str,'%')
#print(result)
匹配汉字文字:
[\u4e00-\u9fa5]
# 匹配非汉字字符:
[^\u4e00-\u9fa5]
# 匹配双字节字符(汉字、中文标点符号等):
[^\x00-\xff]
str1 = input('请输入汉字:')
# str1 = r'[一-禧]+'
search = re.search('[^\u4e00-\u9fa5]+', str1)
if search:
print('不全是汉字')
else:
print('全是汉字')
- 电话号码的验证
tel = '17640171329'
# re_str = r'1[0-9]{10}'
re_str = r'1\d{2,10}'
phone = fullmatch(re_str,tel)
if not phone:
print('不是电话号码')
else:
print('是电话号码')
- 简单的身份证号的验证
re_str = r're_str = r'\d{6}(19\d{2}|200\d|201[0-8])(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[01])\d{3}[\dxX]''
ID = fullmatch(re_str,'513723199609301258')
if not phone:
print('不是身份证号码')
else:
print('是身份证号码')
二、不定项选择题
- 能够完全匹配字符串“(010)-62661617”和字符串“01062661617”的正则表达式包括(A,B,D)
A. “(?\d{3})?-?\d{8}”
B. “[0-9()-]+”
C. “[0-9(-)]\d”
D. “[(]?\d[)-]\d*”
-
能够完全匹配字符串“c:\rapidminer\lib\plugs”的正则表达式包括( B,C )
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”的正则表达式包括( A,C,D)
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”的正则表达式包括(A,D )
:\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”的正则表达式包括( B,C )
A. “a*?b”
B. “a{,2}b”
C. “aa??b”
D. “aaa??b”
网友评论