1

I have a following string:

 161544476293,26220\,1385853403,WLAN-EneTec5,-85,0,0

How to split it with comma but avoid \, case.

In my case above mentioned String should be split as:

161544476293
26220\,1385853403
WLAN-EneTec5
-85
 0
 0

Thanks,

4
  • Just to be clear, why wouldn't -85, 0, and 0 be split apart, too? Commented Jan 30, 2014 at 16:47
  • Are there any other escape sequences involved, e.g. does the format use \\ to escape backslashes too? If you need to ignore \, but still split at \\, then you'll need something more powerful than regular expressions. Commented Jan 30, 2014 at 16:49
  • Where is the split in something like this: 161544476293,26220\\,1385853403,WLAN-EneTec5,-85,0,0 ? Commented Jan 30, 2014 at 16:53
  • This looks like an unusual csv format. Normally anything escaped in a field is surrounded by quotes. Commented Jan 30, 2014 at 17:06

2 Answers 2

4

You can use negative lookbehind:

str.split("(?<!\\\\),");

// OUTPUT: "161544476293", "26220\,1385853403", "WLAN-EneTec5", "-85", "0", "0"


(?<!\\\\) Negative Lookbehind - Assert that it is impossible to match the regex below
\\ matches the character \ literally
, matches the character , literally
Sign up to request clarification or add additional context in comments.

1 Comment

As long as you don't have cases of escaped-bacskslashes like one\\,two see my answer to a different question
3

A pattern like this:

(?<!\\),

Will match any , character not immediately preceded by a \ character. Of course, this is Java, so make sure you escape the \'s in your string literal:

String pattern = "(?<!\\\\),";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.