Split a string with comma neglecting commas inside special characters
For this given input
dog(dog1,dog2,dog3),cat{cat1,cat2,cat3},pe^t"pet1, pet2,pet3",pi*g[pig1,pig2,pig3]
I want the output as
dog(dog1,dog2,dog3)
cat{cat1,cat2,cat3}
pe^t"pet1,pet2,pet3"
pi*g[pig1,pig2,pig3]
I tried the following
Code:
String str = "dog(dog1,dog2),cat{cat1,cat2},pe^t\"pet1,pet2\",pi*g[pig1,pig2]";
if (str.contains(",")) {
String arry[] = str.split(",(? \\w+[})\\]\\\"])");
int len = arry.length;
for (int i = 0; i < len; i++) {
if(arry[i].startsWith("\""))
{
System.err.println(arry[i].replaceAll("^\"|\"$", "").trim());
}
else{
System.err.println(arry[i].trim());
}
}
}
But it will work only for when there are two strings between specialcharacters like the following
"dog(dog1,dog2),cat{cat1,cat2},pe^t\"pet1,pet2\",p i*g[pig1,pig2]"