3

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
Braiam
  • 1
  • 11
  • 47
  • 78
Keren
  • 379
  • 6
  • 16
  • @Marc - I saw that question, but it still wasn't clear to me how to account for both of the conditions I'm looking for. – Keren Aug 03 '16 at 15:35
  • Reopened since this question is about brackets **and** parentheses: a full answer is harder. – Bathsheba Aug 03 '16 at 15:35
  • 1
    @Bathsheba http://stackoverflow.com/questions/28587081/regex-split-on-comma-but-exclude-commas-within-parentheses-and-quotesboth-s – Sotirios Delimanolis Aug 03 '16 at 15:40
  • Nice spot but IMHO it's worth answering that specifically, although your well-found answer might be sufficient for the OP. – Bathsheba Aug 03 '16 at 15:41

1 Answers1

12

You can use the following regex with global flag.

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

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

Community
  • 1
  • 1
Nicolas Henneaux
  • 11,507
  • 11
  • 57
  • 82