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"]))
您可以使用命名捕获组并且在获得匹配后,您将能够获得映射到这些名称的值(使用^{} )。我还建议动态地构建这样一个模式,如OrderedDict。你知道吗
见Python 2.7 demo:
正则表达式看起来像
(?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})
)的值来检查底层模式。你知道吗相关问题 更多 >
编程相关推荐