如何将缺少的值与regex匹配

2024-07-03 07:39:51 发布

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

我有一个表(在本例中是一个字符串)如下所示:

Community            Group / Access      context    acl_filter
---------            --------------      -------    ----------
Community_test-1      network-operator    C0n_text!  T3st-ACL#$
WEWORK                network-operator
RW                    network-admin       _C0n              
YANKS                 network-admin                  my_acl

我必须在不使用其他代码的情况下使用单个正则表达式匹配和解析所有值,但是我在编写匹配缺失值的正则表达式时也遇到了问题。在

现在,让我们忽略前两行,关注实际值:

^{pr2}$

显然,这会导致:

Traceback (most recent call last):
  File "C:\Users\Gabriele\Desktop\prova.py", line 18, in <module>
    group_snmp = match_snmp.groupdict()
AttributeError: 'NoneType' object has no attribute 'groupdict'

虽然这是我想要达到的目标:

{ 0: { 'acl': 'C0n_text!',
       'community': 'Community_test-1',
       'context': 'C0n_text!',
       'group_access': 'network-operator'}
1: { 'acl': '',
       'community': 'WEWORK',
       'context': '',
       'group_access': 'network-operator'}
2: { 'acl': '',
       'community': 'RW',
       'context': '_C0n',
       'group_access': 'network-admin'}
3: { 'acl': 'my_acl',
       'community': 'YANKS',
       'context': '',
       'group_access': 'network-admin'}}

我用不同的正则表达式尝试过很多方法,但都没有成功:(


Tags: textcommunitytestaccessadmincontextgroupnetwork
1条回答
网友
1楼 · 发布于 2024-07-03 07:39:51

引发此错误是因为,当您将原始字符串拆分为show_snmp_community_split时,第一个元素是一个空字符串:''。当与re.match一起使用时,返回None。在

在循环中使用if语句:

for line in show_snmp_community_split:
    snmp_dict = {}
    match_snmp = re.match(show_snmp_community_regex, line)
    if not match_snmp:
        continue
    group_snmp = match_snmp.groupdict()
    community = group_snmp["community"]
    snmp_dict["community"] = community
    group_access = group_snmp["group_access"]
    snmp_dict["group_access"] = group_access
    context = group_snmp["context"]
    snmp_dict["context"] = context
    acl = group_snmp["context"]
    snmp_dict["acl"] = acl
    final_dict[i] = snmp_dict
    i += 1

接下来,由于aclcontext可能有空列,\S+在模式中匹配将失败。将图案更新为:

^{pr2}$

本地测试时的输出:

^{3}$

相关问题 更多 >