Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
94 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...