Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape comma when using String.split

Tags:

I'm trying to perform some super simple parsing o log files, so I'm using String.split method like this:

String [] parts = input.split(",");

And works great for input like:

a,b,c

Or

type=simple, output=Hello, repeat=true 

Just to say something.

How can I escape the comma, so it doesn't match intermediate commas?

For instance, if I want to include a comma in one of the parts:

type=simple, output=Hello, world, repeate=true

I was thinking in something like:

type=simple, output=Hello\, world, repeate=true

But I don't know how to create the split to avoid matching the comma.

I've tried:

String [] parts = input.split("[^\,],");

But, well, is not working.

like image 908
OscarRyz Avatar asked Feb 10 '11 21:02

OscarRyz


1 Answers

You can solve it using a negative look behind.

String[] parts = str.split("(?<!\\\\), ");

Basically it says, split on each ", " that is not preceeded by a backslash.

String str = "type=simple, output=Hello\\, world, repeate=true";
String[] parts = str.split("(?<!\\\\), ");
for (String s : parts)
    System.out.println(s);

Output:

type=simple
output=Hello\, world
repeate=true

(ideone.com link)


If you happen to be stuck with the non-escaped comma-separated values, you could do the following (similar) hack:

String[] parts = str.split(", (?=\\w+=)");

Which says split on each ", " which is followed by some word-characters and an =

(ideone.com link)

like image 80
aioobe Avatar answered Oct 01 '22 19:10

aioobe