-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

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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

working fine but with spaces between chars {"mob": "nonblocked", "type": "user", "allowOrder": true, "prev": 1}}
fixed by result = json.dumps(obj, separators=(',', ':'))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.