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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With