1. 写一个正则表达式判断一个字符串是否是ip地址
规则:一个ip地址由4个数字组成,每个数字之间用.连接。每个数字的大小是0-255
255.189.10.37 正确
256.189.89.9 错误
解:
from re import fullmatch
def main():
re_str = r'(((25[0-5])|(2[0-5]\d)|(1\d{2})|([1-9]\d)|\d)\.){3}'\
r'((25[0-5])|(2[0-5]\d)|(1\d{2})|([1-9]\d)|\d)'
result1 = re.fullmatch(re_str, '192.168.10.3')
print(result1)
result2 = re.fullmatch(re_str, '192.168.12.345')
print(result2)
if __name__ == '__main__':
main()
运行结果:
<_sre.SRE_Match object; span=(0, 12), match='192.168.10.3'>
None
2. 计算一个字符串中所有的数字的和
例如:字符串是:‘hello90abc 78sjh12.5’ 结果是90+78+12.5 = 180.5
解:
import re
def main():
re_str = r'\d+\.?\d*'
result1 = re.findall(re_str, '123asd456')
sum1 = 0
for i in result1:
sum1 += float(i)
print(sum1)
result2 = re.findall(re_str, 'zxc12^&12')
sum1 = 0
for i in result2:
num1 = float(i)
sum1 += num1
print(sum1)
if __name__ == '__main__':
main()
运行结果:
579.0
24.0
3. 验证输入的内容只能是汉字
解:
from re import fullmatch
def main():
re_str = r'[\u4e00-\u9fa5]*'
result1 = fullmatch(re_str, r'阿萨德')
print(result1)
result2 = fullmatch(re_str, 'asd阿萨德')
print(result2)
result3 = fullmatch(re_str, '%^&123阿萨德')
print(result3)
# pass
if __name__ == '__main__':
main()
运行结果:
<_sre.SRE_Match object; span=(0, 3), match='阿萨德'>
None
None
4. 电话号码的验证
解:
from re import fullmatch
def main():
re_str = r'^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$'
result1 = fullmatch(re_str, r'15685825775')
print(result1)
result2 = fullmatch(re_str, '15585819985')
print(result2)
result3 = fullmatch(re_str, 'asd')
print(result3)
# pass
if __name__ == '__main__':
main()
运行结果:
<_sre.SRE_Match object; span=(0, 11), match='15685825775'>
<_sre.SRE_Match object; span=(0, 11), match='15585819985'>
None
5. 简单的身份证号的验证
解:
import re
def main():
re_str = r'(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)'
result1 = re.fullmatch(re_str, '520103199801086711')
print(result1)
result2 = re.fullmatch(re_str, 'zxc12^&12')
print(result2)
if __name__ == '__main__':
main()
运行结果:
<_sre.SRE_Match object; span=(0, 18), match='520103199801086711'>
None
二、不定项选择题
- 能够完全匹配字符串“(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、B、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 )
:\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”