Home > Blockchain >  What would be the regular expression to split this string?
What would be the regular expression to split this string?

Time:06-01

I have this:

st = '"a": "hello", "c": "another, string, with multiple", "b": "hello, world"'

I want to replace the comma by an empty space, but it should only be removed IF the character before it is NOT a double quote (")

So the result of st would be

st = '"a": "hello", "c": "another string with multiple", "b": "hello world"'

CodePudding user response:

If I understand your question right I think that my pseudocode will help you to solve your problem at your required language

for i in st 
    if (st[i] = ",") AND (st[i-1] NOT """)
        POP
    else 
        return 

CodePudding user response:

Your string looks like it is JSON, but with the surrounding braces stripped from it.

The best would be to get the original JSON and work with that, but if you don't have access to that, then restore the JSON, parse it, make the replacements, encode it again as JSON, and strip those braces again:

import json

st = '"a": "hello", "c": "another, string, with multiple", "b": "hello, world"'

d = json.loads("{"   st   "}")
for key in d:
    d[key] = d[key].replace(",", " ").replace("  ", " ")

st = json.dumps(d)[1:-1]
  • Related