Reputation: 2747
I have a json that have the following structure:
{
test1:[value1, value2],
test2:[value3, value4],
.....
}
I am trying to match the key pair value test1:[value1, value2]
. The issue is that I do not always know what the value of the key test1
is. Also, sometimes it might not be an array but just a value. I tried this
"test1":(\[{1})?([^]]+)(\]{1})?(\,)?
but it only works if the value of the keytest1
is a array only. If if remove the square bracket, it will also match the second key test2
. The other issue is that I am using a tool that do not have a json parser
How can go about this?
Upvotes: 1
Views: 2074
Reputation: 425023
Use an alternation to cover both cases:
"test1"\s*:\s*(?:\[[^]]*]|[^,}]+)
See live demo.
Breaking it down:
"test1"\s*:\s*
allows for spaces around the colon(?:...)
is a non-capturing group...|...
is a alternation - like a logic OR
[^]]
is any character that's not a right square bracket\[[^]]*]
is any number of characters that are not a right square brackets, surrounded by square brackets[^,}]+
is any number of characters that are not commas or closing braces (in case the matched term is the last json key:value pairUpvotes: 1
Reputation: 41625
Regular expressions cannot match nested JSON structures.
Just use a proper JSON parser instead. Your code will become both simpler and more correct.
A general reminder: regular expressions can only solve a very limited set of problems. Therefore, whenever you ask for a regular expression, you should rather ask for solving the problem without involving regular expressions at all. Just solve the problem, no matter how.
Upvotes: 2