您可以使用命名的捕获组,并且在获得匹配项之后,您将能够获取映射到这些名称的值(groupDict()).我还建议动态地将这种模式构建为OrderedDict.
import re, collections
# Define the pattern parts with named capturing groups
parts = [('p1', r'(?P[ABC]{1,3})'),
('p2', r'(?P.{0,2})'),
('p3', r'(?P[DEFG])'),
('p4', r'(?P.{2,3})'),
('p5', r'(?PV)')]
# 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),一旦找到匹配项,您将得到类似
{‘p2’:’X’,’p3’:’D’,’p1’:’A’,’p4’:’XX’,’v’:’V’}}.然后,您可以始终使用“ {} => {}”.format(m.group(“ p1”),pod [“ p1”])(例如A =>(?P< ; p1> [ABC] {1,3})).