python - 无法使用 python match() 解析字符串 - 出现错误 AttributeError : 'NoneType' object has no attribute 'group'

标签 python regex

我有一本字典,它是 aerospike info 命令的输出。我需要从中解析一个值。

我已将其设置为 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'

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

最佳答案

你需要纠正你的模式。末尾的 /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 模式。

关于python - 无法使用 python match() 解析字符串 - 出现错误 AttributeError : 'NoneType' object has no attribute 'group' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583937/

相关文章:

regex - 从数据框中删除百分比

c# - 字符串中多个数字的正则表达式命名捕获

javascript - 如何从外部 JS 文件调用 Python 函数?

python - 在 Python 中高效迭代任意深度字典树

python - 拆分 df 中的每一行并为每个元素添加值

MySQL 正则表达式返回字符串而不是 Y/N

javascript 验证仅适用于字母值

python - cx_Oracle 和异常处理 - 好的做法?

python - 'Roster_Name = Roster_List[1] IndexError : list index out of range", 列表 "Roster_List"有 3 个元素? - Python

regex - 我的 scala 正则表达式模式是正确的表示方式吗?