Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match between open and close brackets if not empty?

Tags:

string

regex

Using a regular expression, given the following text how can I match the contents between the square brackets but only if not empty?

{
  "key": [  
   ],

   "match": [
      1,
      2,
      3,
      4
   ]
}

/:\s*\[([^\]\[]+)\]/g: This is my attempt, and while it matches anything within the brackets including whitespace (desired) I can't work out how to only match between brackets that are essentially an empty array (i.e.) not just whitespace.

In the text above I want to match the contents of the second key but not the whitespace of the first key.

It's important that I capture the white space as well as I want to preserve the formatting but I don't want to capture the contents between the brackets if there is none or is only whitespace/newlines etc.

You can see and play with my regex here: https://regex101.com/r/iN9cD5/3

THANKS.

like image 662
Camsoft Avatar asked Feb 12 '26 07:02

Camsoft


1 Answers

You can leverage a negative lookahead:

:\s*\[(?!\s*])([^\]\[]+)\]
       ^^^^^^^

See demo

The (?!\s*]) will fail a match if there are just whitespace symbols or nothing after [ before the next ].

In PCRE regex flavor, you can get rid of some redundant escaping symbols and use

:\s*\[(?!\s*])([^][]+)]`

See another demo. The [^][] matches any character but [ and ] due to smart placing of ] right after the character class opening [ and [ does not have to be escaped in a PCRE regex character class.

like image 123
Wiktor Stribiżew Avatar answered Feb 17 '26 01:02

Wiktor Stribiżew