Reputation: 10284
I have a dictionary which is output of an aerospike info command. I need to parse a value from it.
I have set it as a string to the response
variable as shown below. However, it's type still shows as dictionary. So, as suggested in this answer, I have dumped it to string type and then tried to call match()
(because it expects string parameter). However, I am still getting this error.
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)
Output -
<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'
I am getting the desired output using the same string and regex pattern - https://regex101.com/r/ymotqe/1
Upvotes: 1
Views: 1476
Reputation: 51643
You need to correct your pattern. The /gm
part at the end corresponds to flags for regex. Some other things '/'
are also not needed.
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)
Output:
"{'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
When using regex101.com you should also switch to python
mode.
Upvotes: 2