-1
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

  • 3
    Wouldn't it be easier to parse the JSON, manipulate it, and dump it back as a string? Why use regexes here? – Nick ODell May 04 '23 at 03:27
  • i tho this would be easier at least for me – Annie Chain May 04 '23 at 03:31
  • 2
    Okay. What's the intended output? You mention that you want multiple replacements - what should the replaced value be? – Nick ODell May 04 '23 at 03:32
  • output = {"allowOrder":true,""type":"user","allowOrder":true,"prev":1} i need to multiple change mob and allowOrder with different values – Annie Chain May 04 '23 at 03:38
  • 1
    This is easy: `import json; data = json.loads(text); data['allowOrder'] = True; data['mob'] = 'nonblocked'; data_dump = json.dumps(data)`. [This](https://stackoverflow.com/a/32155765) is not. – InSync May 04 '23 at 03:42

1 Answers1

1

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
Adam Smith
  • 52,157
  • 12
  • 73
  • 112