我如何使用re.search查找所有以'ly'和'ed'结尾的单词

时间:2018-12-10 03:11:51

标签: python

text =“他被精心伪装,但很快被警察抓捕。” 汇入

def re_search(模式):

result, start = [], 0
#insert your code begin
length = len(text)
pattern1 = re.compile(pattern)
while start < length:
    matchresult1 = pattern1.search(text,start)
    all = matchresult1.group(0)
    s = matchresult1.start()
    e = matchresult1.end()
    result.append((all,s,e))
    start = e  
    if not matchresult1:
        break     
return result

模式= r'(\ w +)(ly | ed)' re_search(pattern)

我期望的= [('仔细地',7,16),('变相的',17,26),('被捕获的',31,39),('迅速',40,47)]

1 个答案:

答案 0 :(得分:0)

python re模块具有finditer函数(https://docs.python.org/3/library/re.html#re.finditer),该函数提供了一个迭代器来产生匹配对象。

for match in re.finditer(pattern, text): 
    print(match)  

输出:<_sre.SRE_Match object; span=(7, 16), match='carefully'> <_sre.SRE_Match object; span=(17, 26), match='disguised'> <_sre.SRE_Match object; span=(31, 39), match='captured'> <_sre.SRE_Match object; span=(40, 47), match='quickly'>