Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 668
Selphiron Avatar asked Nov 23 '16 17:11

Selphiron


People also ask

How do I split a string based on space but take quoted Substrings as one word?

How do I split a string based on space but take quoted Substrings as one word? \S* - followed by zero or more non-space characters.

How do you split a string with comma separated?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you ignore a comma in a string in python?

sub() function to erase commas from the python string. The function re. sub() is used to swap the substring. Also, it will replace any match with the other parameter, in this case, the null string, eliminating all commas from the string.

How do you split quotation marks?

Question marks and exclamation marks go inside the quotation marks when they are part of the original quotation. For split quotations, it's also necessary to add a comma after the first part of the quotation and after the narrative element (just like you would with a declarative quotation).


1 Answers

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

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

This will capture each piece of data as group 1.

like image 105
Whothehellisthat Avatar answered Sep 23 '22 16:09

Whothehellisthat