Matching and replace multiple strings in python

Question:

import re
text = '{"mob":"1154098431","type":"user","allowOrder":false,"prev":1}'

newstring = '"allowOrder":true,"'
#newstring = '"mob":"nonblocked",'

reg = '"allowOrder":(.*?),"|"mob":"(.*?)",'
r = re.compile(reg,re.DOTALL)
result = r.sub(newstring, text)

print (result)

im trying to matching and replacing multiple regex patterns with exact values can someone help me to achieve this

Asked By: Annie Chain

||

Answers:

You should parse the JSON rather than trying to use regex for this. Luckily that’s real straightforward.

import json

text = '{"mob":"1154098431","type":"user","allowOrder":false,"prev":1}'
obj = json.loads(text)  # "loads" means "load string"

if 'allowOrder' in obj:
    obj['allowOrder'] = True
if 'mob' in obj:
    obj['mob'] = 'nonblocked'

result = json.dumps(obj)  # "dumps" means "dump to string"

assert '{"mob": "nonblocked", "type": "user", "allowOrder": true, "prev": 1}' == result
Answered By: Adam Smith
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.