Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin String.split, ignore when delimiter is inside a quote

I have a string:

Hi there, "Bananas are, by nature, evil.", Hey there.

I want to split the string with commas as the delimiter. How do I get the .split method to ignore the comma inside the quotes, so that it returns 3 strings and not 5.

like image 266
PeptideWitch Avatar asked Dec 07 '22 14:12

PeptideWitch


1 Answers

You can use regex in split method

According to this answer the following regex only matches , outside of the " mark

,(?=(?:[^\"]\"[^\"]\")[^\"]$)

so try this code:

str.split(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)".toRegex())
like image 148
Mosius Avatar answered Dec 11 '22 10:12

Mosius