regex 如何找到匹配并打印

wkftcu5l  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(130)

如何找到匹配并打印它。我用正则表达式来实现,但无法匹配
我有一个字符串,我需要找到匹配和打印

s='flowerflowflight'

预期输出:

fl

我的编码:

import re 

print(re.search(r'[a-z]\+',s))
t2a7ltrp

t2a7ltrp1#

为什么不使用compile:

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

相关问题