正则表达式命名组

2024-04-25 20:18:39 发布

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

我想要一个正则表达式,它捕获像“James Allen”和“Allen,James”这样的名字,并将命名组放在最前面和最后。 以下是我所拥有的:

(?P<first>\w+), (?P<last>\w+)|(?P<last>\w+) (?P<first>\w+)

但它会导致子模式命名错误。如何修复它,使它只匹配其中一个模式。我想保留组名“first”和“last”。你知道吗


Tags: 错误模式名字命名firstlastjamesallen
1条回答
网友
1楼 · 发布于 2024-04-25 20:18:39

命名符号组需要名称。它的形式是(?P<name>...)。在您的示例中,您忘记提供组的名称。你知道吗

不幸的是,不能重用组名,因此出现以下错误。你知道吗

re.compile(r'(?P<last>\w+), (?P<first>\w+)|(?P<first>\w+) (?P<last>\w+)')
# sre_constants.error: redefinition of group name 'first' ...

发生上述错误的原因是re不够聪明,无法知道每个名称中只有一个匹配。因此,您必须捕获模式,然后提取firstlast。你知道吗

import re

def get_name(name):
    match = re.match(r'(\w+), (\w+)|(\w+) (\w+)', name)

    return {'first': match[2] or match[3], 'last': match[1] or match[4]}

print(get_name('James Allen'))
print(get_name('Allen, James'))

输出

{'first': 'James', 'last': 'Allen'}
{'first': 'James', 'last': 'Allen'}

相关问题 更多 >