Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matching and replace multiple strings in python

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading