Matching and replace multiple strings in python

Annie Chain
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

Adam Smith

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related