2

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.

Melissa Stewart
  • 3,483
  • 11
  • 49
  • 88

2 Answers2

4

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']
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
1

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

Change:

\\"

To:

\"
Jacob G.
  • 28,856
  • 5
  • 62
  • 116