Selphiron
Selphiron

Reputation: 929

Split string by comma but ignore commas in brackets or in quotes

I have a string like hello, "darkness, my", (old, friend) and I want this splitted result:
hello
"darkness, my"
(old, friend)

I found a way to ignore the commas in "-marks (,?=([^\"]*\"[^\"]*\")*[^\"]*$) and another way to ignore the commas in brackets (,(?=[^\\)]*(?:\\(|$))).
When I use the first, I get:
hello
"darkness, my"
(old
friend)
And when I use the second, I get:
hello
"darkness
my"
(old, friend)

But how do I combine these two solutions?

Upvotes: 5

Views: 7818

Answers (1)

Whothehellisthat
Whothehellisthat

Reputation: 2152

Probably easier to match the parts, rather than splitting them.

\s*("[^"]*"|\([^)]*\)|[^,]+)

This will capture each piece of data as group 1.

Upvotes: 3

Related Questions