Zag Gol
Zag Gol

Reputation: 1076

java split string into array by a few charaters

got a string that looks like this:

"abc", "def", "ghi"

I need to split string to array like this:

abc
def
ghi

I tried:

String [] strArray = sb.toString().split(" ,\""); 

but it doesn't work.

Upvotes: 1

Views: 61

Answers (2)

venergiac
venergiac

Reputation: 7717

the split method accept regex

consider the following code

str.split("(\", \")+|(\")+")

you will get a four elements array

[, abc, def, ghi]

As suggested by Zaheer you can remove the first "

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28538

You firstly need to remove first and last quotation from string:

sb = sb.substring(1, sb.length() - 1); //remove first and last character

after above line of code your sb will be:

abc", "def", "ghi

and then try this regex:

String[] strArray = sb.split("\"\\s*,\\s*\"");

its split on the basis of quote (any no of space) comma (any no of space) quote

Upvotes: 1

Related Questions