Siva Siva - 2 months ago 7x
Java Question

Split strings based on single occurrence of delimiter but not double in Java

How to split a string using single occurrence of a delimiter disregarding multiple occurrences?

For example, if the string contains

aaa, bbb,,ccc, ddd

I would like to split the string as follows:




Tried using Regex with split() but unable to acquire the desired result.

Came across the solution in Javascript here: Split string with a single occurence (not twice) of a delimiter in Javascript. Is it possible to achieve the same in Java, with or without Regex?


String.split() accepts regular expressions as delimiters so you could use the following pattern :


This regex matches a comma that is neither preceded nor followed by a comma.

You can see it in action here :

If you want to trim the leading spaces at the same time you can use (?<!,),(?!,) * as mentioned by Nicolas Filotto.