代码之家  ›  专栏  ›  技术社区  ›  Sandeepan Nath

无法使用python match()分析字符串-获取错误attributeError:“nonetype”对象没有属性“group”

  •  1
  • Sandeepan Nath  · 技术社区  · 7 年前

    我有一本词典,它是Aerospike信息命令的输出。我需要从中解析一个值。

    我把它当作一根绳子 response 变量如下所示。但是,它的类型仍然显示为字典。因此,正如中建议的那样 this answer ,我已将其转储为字符串类型,然后尝试调用 match() (因为它需要字符串参数)。但是,我仍然得到这个错误。

    respone = "{'BB912E94CDE0B0E': (None, 'n_objects=179:n-bytes-memory=0:stop-writes-count=0:set-enable-xdr=use-default:disable-eviction=true:set-delete=false;\n')}"
    p = "/.*\'n_objects=([0-9]+)\:.*/gm"
    stringResponse = json.dumps(response)
    print type(response)
    print stringResponse
    print type(stringResponse)
    print re.match(p,stringResponse).group(1)
    

    输出-

    <type 'dict'>
    {"BB912E94CDE0B0E": [null, "n_objects=179:n-bytes-memory=0:stop-writes-count=0:set-enable-xdr=use-default:disable-eviction=true:set-delete=false;\n"]}
    <type 'str'>
    Traceback (most recent call last):
      File "Sandeepan-oauth_token_cache_complete_sanity_cp.py", line 104, in <module>
        print re.match(p,stringResponse).group(1)
    AttributeError: 'NoneType' object has no attribute 'group'
    

    我使用相同的字符串和regex模式获得所需的输出- https://regex101.com/r/ymotqe/1

    1 回复  |  直到 7 年前
        1
  •  2
  •   Patrick Artner    7 年前

    你需要纠正你的模式。这个 /gm 末尾的部分对应于regex的标志。其他一些事情 '/' 也不需要。

    import json
    import re
    
    # fixed variable name
    response = "{'BB912E94CDE0B0E': (None, 'n_objects=179:n-bytes-memory=0:stop-writes-count=0:set-enable-xdr=use-default:disable-eviction=true:set-delete=false;\n')}"
    
    # fixed pattern
    p = ".*'n_objects=([0-9]+):.*"
    stringResponse = json.dumps(response)
    print stringResponse
    print type(response)
    
    # fixed flags parameter (but you do not need it in your example)
    print re.match(p,stringResponse, flags=re.M).group(1)
    

    输出:

    "{'BB912E94CDE0B0E': (None, 'n_objects=179:n-bytes-memory=0:stop-writes-count=0:set-enable-xdr=use-default:disable-eviction=true:set-delete=false;\n')}"
    <type 'str'>
    179
    

    使用regex101.com时,还应切换到 python 模式。