可能是个令人困惑的标题,让我解释一下。。你知道吗
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
上迭代?你知道吗
将
fruit_compile.search(myfavourite)
的结果保存到变量中。你知道吗我注意到您已经保存了
fruit_compile.search
的结果,但是只有在检查第一个调用是否返回None
之后。你知道吗您已经在一条评论中阐明,您正在寻找与字符串匹配的替代模式。你知道吗
一种方法是通过使用
matchObject.groups()
找到正确替代方案的索引。它是一个元组,其中每个不匹配的组都是None
。你知道吗找到非
None
值的索引,就可以从原始水果列表中检索到正确的项目。这显然涉及到一种或另一种方式的迭代,这与你的上一句话背道而驰。你知道吗您必须使用此方法为每个备选方案创建一个组。你知道吗
另一种选择是使用
for
循环,尝试逐个匹配候选对象。你知道吗我不确定这对整体表现有何影响。你知道吗
注意:如果“模式”只是常量字符串,那么首先就不应该使用正则表达式。我的回答基于这样一个假设:为了清晰起见,您的示例代码已经简化了。你知道吗
在Python文档页面中有一个关于re的公式:
其中m是match对象(在您的例子中它将是match),g是可选的组参数。你知道吗
你需要使用
<compiled_obj>.pattern
相关问题 更多 >
编程相关推荐