user3841581
user3841581

Reputation: 2747

Regex to match an the value of a json entry that may contains square brackets []

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

Answers (2)

Bohemian
Bohemian

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 pair

Upvotes: 1

Roland Illig
Roland Illig

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

Related Questions