import re
# you get tru or false
patterns = ['fl']
s = 'flowerflowflight'
for pattern in patterns:
if re.search(pattern, s):
print("found a match")
else:
print("not found a match")
# print a list of match
s='flowerflowflight'
pattern = re.compile('fl')
result=pattern.findall(s)
print('first list element',result[0])
# print the first match
result = re.match('fl', s)
print('first match', result.group())
# all match emements in a list
s1 = ['flowerflowflight','fl']
for elem in s1:
p = re.match('fl', elem)
print('all matches in a list', p.group())
# print all matches
s = 'flowerflowflight'
res = re.finditer('fl', s)
for hit in res:
print('iter all matches', hit.group())
输出:
found a match
first list element fl
first match fl
all matches in a list fl
all matches in a list fl
iter all matches fl
iter all matches fl
iter all matches fl
1条答案
按热度按时间t2a7ltrp1#
为什么不使用compile:
输出: