I'm trying to form a regex that will match a string that "looks" like an array.
- Must start with
[
,{
or(
- Must end with
]
,}
, or)
- Does not matter if start and end use same bracket (e.g.
(....}
is fine) - Items are separated by commas
- All white-space types are ignored
- Empty arrays must be accepted
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.