Keren
Keren

Reputation: 539

Split string by comma if not within square brackets or parentheses

I have a long string, and I want to set it to an array by splitting it by the comma as long as the comma is not within square brackets or parentheses. I've tried a couple of variations but not getting exactly what I'm looking for...

Example 1:

Harry Potter, Hermione, (Severus, Snape)
Returns:
Harry Potter
Hermione
Severus, Snape

Example 2:

Harry Potter, [and, the chamber, of secrets], Hermione, (Olivanders, Wands)
Returns:
Harry Potter
and, the chamber, of secrets
Hermione
Olivanders, Wands

Upvotes: 3

Views: 5558

Answers (1)

Nicolas Henneaux
Nicolas Henneaux

Reputation: 12215

You can use the following regex with global flag.

,(?![^\(\[]*[\]\)])

Here is a demo. It is inspired by https://stackoverflow.com/a/9030062/1630604.

Upvotes: 13

Related Questions