首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法使用python match()分析字符串-获取错误组:'NoneType‘对象没有属性’AttributeError‘

无法使用python match()分析字符串-获取错误组:'NoneType‘对象没有属性’AttributeError‘
EN

Stack Overflow用户
提问于 2018-07-30 03:43:05
回答 1查看 924关注 0票数 1

我有一个字典,它是一个航空信息命令的输出。我需要从中解析一个值。

我已经将它设置为response变量的字符串,如下所示。但是,它的类型仍然显示为字典。因此,按照this answer中的建议,我将其转储为string类型,然后尝试调用match() (因为它需要string参数)。然而,我仍然收到这个错误。

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'

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-30 03:50:23

你需要纠正你的模式。末尾的/gm部分对应于正则表达式的标志。其他一些东西'/'也是不需要的。

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模式。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51583937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档