按字符串匹配的正则表达式中的返回组

2024-10-01 02:26:25 发布

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

假设我们有以下正则表达式:

[ABC]{1,3}.{0,2}[DEFG].{2,3}V

我们可以使用Python的re模块测试它是否匹配以下字符串:

AXDXXV

确实匹配。然后,使用Python,我们如何检索与字符串的每个部分匹配的正则表达式的每个部分?你知道吗

例如,以下输出列表将起作用:

[ '[ABC]{1,3}', '.{0,2}', '[DEFG]', '.{2,3}', 'V' ]

Tags: 模块字符串re列表abcdefgaxdxxv
1条回答
网友
1楼 · 发布于 2024-10-01 02:26:25

您可以使用命名捕获组并且在获得匹配后,您将能够获得映射到这些名称的值(使用^{})。我还建议动态地构建这样一个模式,如OrderedDict。你知道吗

Python 2.7 demo

import re, collections

# Define the pattern parts with named capturing groups
parts = [('p1', r'(?P<p1>[ABC]{1,3})'),
    ('p2', r'(?P<p2>.{0,2})'),
    ('p3', r'(?P<p3>[DEFG])'),
    ('p4', r'(?P<p4>.{2,3})'),
    ('p5', r'(?P<v>V)')]
# Create and init the OrderedDict
pod = collections.OrderedDict(parts)
# Build the pattern from values (in Python 3, use list(pod.items()) )
reg = "".join([v for k,v in pod.items()])
test_str = "AXDXXV"
# Find a match
m = re.search(reg, test_str)
if m:
    # If a match is found, get the groupdict()
    m_dict = m.groupdict()
    print(m_dict)
    print("{} => {}".format(m.group("p1"), pod["p1"]))

正则表达式看起来像(?P<p1>[ABC]{1,3})(?P<p2>.{0,2})(?P<p3>[DEFG])(?P<p4>.{2,3})(?P<v>V),一旦找到匹配项,就会得到 {'p2': 'X', 'p3': 'D', 'p1': 'A', 'p4': 'XX', 'v': 'V'}。然后,您可以始终使用带有"{} => {}".format(m.group("p1"), pod["p1"])(例如A => (?P<p1>[ABC]{1,3}))的值来检查底层模式。你知道吗

相关问题 更多 >