1.匹配hi开头的单词,只需要匹配一次。s=‘hi ,his name is history!’
import re
s=‘hi ,his name is history!’
print(re.match(r"hi\w*",s))
执行结果:
<_sre.SRE_Match object; span=(0, 2), match=‘hi’>
import re
s=‘hi ,his name is history!’
print(re.search(r"hi\w*",s))
执行结果:
<_sre.SRE_Match object; span=(0, 2), match=‘hi’>
2.匹配hi开头的单词,需要匹配二次。s=‘hi ,his name is history!’
import re
s=‘hi ,his name is history!’
print(re.findall(r"hi\w*",s)[0:2])
执行结果:
[‘hi’, ‘his’]
3.匹配hi开头的单词,需要返回全部匹配结果。s=‘hi ,his name is history!’
import re
s=‘hi ,his name is history!’
print(re.findall(r"hi\w*",s))
执行结果:
[‘hi’, ‘his’, ‘history’]
4.匹配以ing或者noon为结尾的单词。s=‘good morning,good afternoon,good evening’
import re
s=‘good morning,good afternoon,good evening’
print(re.findall(r"\w*ing|noon\b",s))
执行结果:
[‘morning’, ‘noon’, ‘evening’]
5.匹配包含tom的内容(忽略大小写)并返回匹配的个数。s=‘My name is Tom, and you can call me Tommy too’。
import re
s=‘My name is Tom, and you can call me Tommy too,tomorrow’
print(re.findall(r"\w*[t|T]om\w*",s))
执行结果:
[‘Tom’, ‘Tommy’, ‘tomorrow’]
import re
s=‘My name is Tom, and you can call me Tommy too,tomorrow’
print(re.findall(r"\wtom\w",s,re.I))
执行结果:
[‘Tom’, ‘Tommy’, ‘tomorrow’]
6.匹配以in开头单词的后半部分(如integrated–>返回tegrated)。s=‘introduction,i am interesting boy’
import re
s=‘introduction,i am interesting boy’
print(re.findall(r"(?<=in)\w*",s))
执行结果:
[‘troduction’, ‘teresting’]
7.匹配不包含连续字符串abc的单词。s=‘abcddd qweabee ddabc abc cba’
import re
result=[]
s=‘abcddd qweabee ddabc abc cba’
print(re.findall(r"\w+",s))
result1=re.findall(r"\w+",s)
print(re.findall(r"\wabc\w",s))
result2=re.findall(r"\wabc\w",s)
for i in result1:
if i not in result2:
result.append(i)
print(result)
没有想出一个正则能解决的办法
8.匹配网址格式,如www.baidu.com或者https://www.baidu.com/
import re
s=‘https://www.baidu.com/’
print(re.findall(r"w{3}.\w*.\w*",s))
执行结果:
[‘www.baidu.com’]
9.匹配指定格式的电话号码,如010-1234-5678或者1234-5678
10.
import re
s = ‘010-1234-5678 1234-567810’
print(re.findall(r"(?:\d{3,4}-)?\d{4}-\d{4,6}",s))
执行结果:
[‘010-1234-5678’, ‘1234-567810’]
10.随机生成10位数字,如果10位数字中有任意3位连续数字,返回666,否则返回0
import re
import random
num = random.randint(1000000000,9999999999)
print(num)
if re.search(r’(\d)\1\1’,str(num)):
print(“666”)
else:
print(“0”)