python正则匹配字符串_python-正则表达式中的返回组由字符串匹配

您可以使用命名的捕获组,并且在获得匹配项之后,您将能够获取映射到这些名称的值(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})).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值