How to parse Json using Regex?

2019-03-03 20:07发布

问题:

I want to parse this json data with regex. But, i could not. I tried like this module.getid(.*), but no working.

Only, I want to take this part -> module.getid(...)

module.getid([{"id":"44423"}]); module.getresult([{"result":"false"}]);

How can i do it?

回答1:

Try this if you want to capture the first (demo):

/module.getid\((.*?)\); *module.getresult(?:.*?)\);$/m

If you want to capture both json strings (demo):

/module.getid\((.*?)\); *module.getresult(.*?)\);$/m


回答2:

Well, to work from that new string you gave us:

module.getid([{"id":"44423", "code":"mod_editor"}]);

Here's a regular expression that nicely compartmentalizes all the data from the line provided

m/module\x2egetid\x28\x5b\x7b\x22(?<key1>[^\x22]+)\x22\x3a\x22(?<value1>\d+)\x22\x2c\s+\x22(?<key2>[^\x22]+)\x22\x3a\x22(?<value2>[^\x22]+)\x22/

You can reference the fields by using the named captures or the number of the capture, whichever you prefer.

in this case to just return the portion of data which in this string is 44423 you could either reference capture number '2' or capture name 'value1'.

I'm not sure which language you're using to 'parse' this data, so I couldn't give you an actual snippet of working code.