Search code examples
pythonpython-re

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

  • 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