想检查python正则表达式匹配(组)内部条件的结果吗

2024-09-23 16:26:59 发布

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

我想检查是否有一个正则表达式匹配成功。如果是的话,我想访问比赛中的组。如果我不需要团队,我可以这样做:

if re.match(pobj1,string):
    # First match worked
elif re.match(pobj2,string):
    # First match failed, but second one worked.
[...]

由于我没有将匹配结果分配给任何对象,因此我不知道如何访问作为匹配一部分的任何组。因此,我将匹配项赋给条件之前的一个变量。但这意味着我每次都在进行所有的比赛,而不仅仅是必要的比赛

mobj1 = re.match(pobj1,string)
mobj2 = re.match(pobj2,string)  # Might be expensive
if mobj1:
    # First match succeeded.  Use the match information
    primary_list.append(mobj1.group(1))
elif mobj2:
    # First match failed, but second one worked.  Use info from #2.
    secondary_list.append(mobj2.group(1))
[...]

如何只运行必要的匹配,而在以后仍然能够从该匹配访问组


Tags: restringifmatchonebutfirstsecond
2条回答

我会列出你的对象,用一个循环遍历它们,一旦找到匹配的对象就打断它

for o in list_of_objects:
    matches = re.match(o,string)
    if matches:
        break

您可以定义一个模式列表并找到第一个与^{}匹配的模式

>>> import re
>>> patterns = [re.compile('a.c'), re.compile('1.3'), re.compile('4.6')]
>>> next((p for p in patterns if p.match('abc')), None)
re.compile('a.c')
>>> next((p for p in patterns if p.match('436')), None)
re.compile('4.6')
>>> next((p for p in patterns if p.match('XYZ')), None)

None作为next的第二个参数用于避免StopIteration:

>>> next(p for p in patterns if p.match('XYZ'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

相关问题 更多 >