0

I have a string like this abc & "def&ghi" & jkl & "mno&pqr" and want to do a split aroung &, but i don't want to split words within double quotes.

Output should be abc, "def&ghi", jkl, "mno&pqr".

I tried doing a split("&") on that string, but that's also splitting the words within double quotes.

Whats the best way of doing this?

vjk
  • 1,861
  • 5
  • 26
  • 38
  • 2
    Look at the accepted answer [here](http://stackoverflow.com/questions/1757065/java-splitting-a-comma-separated-string-but-ignoring-commas-in-quotes), and replace the `,` with a `&` – Perception Mar 06 '13 at 02:32

3 Answers3

4

It looks like you should use something like a csv parser since those are programmed exactly to handle the issue of " " escaping.

If this is homework and you are not allowed to use production tools, then you should follow the advice in What have you tried?

djechlin
  • 54,898
  • 29
  • 144
  • 264
0

if there was a white space between the & quote like you mentioned above

abc & "def&ghi" & jkl & "mno&pqr"

then you can use .split(" & "); to also trim the white space.

goravine
  • 258
  • 3
  • 11
0

I agree that CSV parser is the solution, but as a matter of principle:

    String s = "abc & \"def&ghi\" & jkl & \"mno&pqr\"";
    String[] a = s.split("(?=.*[^\"] )&");
    System.out.println(Arrays.toString(a));

output

[abc ,  "def, ghi" ,  jkl ,  "mno&pqr"]
Evgeniy Dorofeev
  • 124,221
  • 27
  • 187
  • 258