Melissa Stewart
Melissa Stewart

Reputation: 3605

Splitting a string into a list in Java

I'm trying to split a string into a list base on :,"{[ }] This is my code,

List<String> list = new ArrayList<String>(Arrays.asList(line.split("{ | } | \\"| : | [ | ]|,")));

Which isn't compiling. I'm not really adept at regex. Any help please.

Upvotes: 2

Views: 2308

Answers (2)

Do you mean you want it split "whenever you see : or , or " or { or [ or } or ]"? If so, you really don't need to say much more than:

.split("[:,\"{\\[ }\\]]")

I.e. "split on any character in the following character class definition: :,"{[ }]", where we use the standard regexp character class definition syntax ([...]) with appropriate escaping.

Normally this means a regex that looks like /[:,"{\[ }\]]/ but because you're writing a regex inside of a normal string, more escapes are needed: " needs regular string escaping so your string doesn't end prematurely (so that becomes \"), and [ and ] are active characters in the regexp, so they need \ before them in the regex. However, we can't just put \ in the string and have it work because \ is the escape character, so we need to "escape the escape" which means using \\ (giving \\[ and \\]).

String[] result = "a:b,c\"d{e[f g}h]i".split("[:,\"{\\[ }\\]]");
System.out.print(result.length);
// => result has 9 elements in it, ['a',...,'i']

Upvotes: 4

Jacob G.
Jacob G.

Reputation: 29700

It's not compiling because you didn't escape the quotation mark, but the backslash itself.

Change:

\\"

To:

\"

Upvotes: 1

Related Questions