gpt4 book ai didi

python - 如何从 re.compile 获取匹配的对象,但不是匹配组

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:01 26 4
gpt4 key购买 nike

可能是一个令人困惑的标题,所以让我解释一下..

import re
fruit_list = ['apples', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
myfavourite = 'Apples are really nice'
fruit_compile = re.compile('|'.join(fruit_list),flags=re.IGNORECASE)

if fruit_compile.search(myfavourite):
match = fruit_compile.search(myfavourite)
print(match.group())

现在使用上面的内容,我可以使用 match.group() 获取匹配的字符串(这将是 Apples)。

如何从 fruit_compile (最初为 fruit_list)(将是 apple)获取匹配的对象作为字符串,而无需迭代返回fruit_list

最佳答案

在 Python 文档页面中确实有一个解决这个问题的方法:

m.string[m.start(g):m.end(g)]

其中 m 是匹配对象(在您的情况下是匹配),g 是可选的组参数。

关于python - 如何从 re.compile 获取匹配的对象,但不是匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45464590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com