如何从中获取对象重新编译匹配,但不是匹配组

2024-10-02 20:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

可能是个令人困惑的标题,让我解释一下。。你知道吗

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上迭代?你知道吗


Tags: 字符串importre标题searchmatchgrouplist
3条回答

fruit_compile.search(myfavourite)的结果保存到变量中。你知道吗

finding = fruit_compile.search(myfavourite)
if finding:
   doSomethingWithFruit(finding.group(0))

我注意到您已经保存了fruit_compile.search的结果,但是只有在检查第一个调用是否返回None之后。你知道吗


您已经在一条评论中阐明,您正在寻找与字符串匹配的替代模式。你知道吗

一种方法是通过使用matchObject.groups()找到正确替代方案的索引。它是一个元组,其中每个不匹配的组都是None。你知道吗

找到非None值的索引,就可以从原始水果列表中检索到正确的项目。这显然涉及到一种或另一种方式的迭代,这与你的上一句话背道而驰。你知道吗

您必须使用此方法为每个备选方案创建一个组。你知道吗

'(' + ')|('.join(fruits) + ')'

另一种选择是使用for循环,尝试逐个匹配候选对象。你知道吗

patterns = [re.compile(p) for p in fruits]
for p in patterns:
  if p.match(string):
    return p.pattern

我不确定这对整体表现有何影响。你知道吗

注意:如果“模式”只是常量字符串,那么首先就不应该使用正则表达式。我的回答基于这样一个假设:为了清晰起见,您的示例代码已经简化了。你知道吗

在Python文档页面中有一个关于re的公式:

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

其中m是match对象(在您的例子中它将是match),g是可选的组参数。你知道吗

你需要使用<compiled_obj>.pattern

searched_pattern = fruit_compile.pattern
print (searched_pattern)

'apples|banana|peach|plum|pineapple|kiwi'

相关问题 更多 >