I'm trying to form a regex that will match a string that "looks" like an array.
[
, {
or (
]
, }
, or )
(....}
is fine)What I came up with initially was
'/\s*[\[|\{|\(]\s*\w+\s*[,\s*\w+]*\s*[\]|\}|\)]\s*/'
Unfortunately this doesn't accept an empty array. So I tried another
'/\s*[\[|\{|\(][\s*\w+\s*]?[,\s*\w+]*\s*[\]|\}|\)]\s*/'`
This one allows the empty array but also allows an array that starts with a comma after the opening bracket (e.g. [, item, item]
).
What I'm doing currently is using two different regexes and checking that one or the other matches. The other regex is similar to the first one I mentioned here but only allows zero or more whitespace characters between the open and closing markers.
I've used spaces and newlines below for clarity. They should be removed or use a regex option that ignores them. I find it easier to develop regexs this way.
[\[\{\(]
\s*
(
|
\w+\s*
(,\s*\w+\s*)*
)
[\]\}\)]
This has not been tested, but I hope it's very close.
Try treating an empty array as a special case and or it with the populated array regex you have already. Something like (untested):
'(?:[\({[]\s*[\)}\]]|/\s*[\[|\{|\(]\s*\w+\s*[,\s*\w+]*\s*[\]|\}|\)]\s*)/'