Question: I have a string of comma-delimited characters that I'm splitting. Some of these characters, though, could be commas. For example:

`test = "a,b,c,d,,,e,f,g"`

I know that `(?<!,),` is the regular expression for "any commas not preceded by a comma", and `,(?!,)` is the regular expression for "any comma followed by a comma". Could someone point me in the right direction and show me how to combine these two. The desired output is: 

```
a  
b  
c  
d  
,  
e  
f  
g  

```

The program is in Java, so if someone knows a function specific to Java, that works, too.

Answer: 
Split by `,` only if there is no `,` before or after it .

```
    String str = "a,b,c,d,,,e,f,g";
    String regex = "(?<!,),|,(?!,)";

    for(String s : str.split(regex)) {            
        System.out.println(s);
    }

```

Output:

> 
> 
> ```
> a
> b
> c
> d
> ,
> e
> f
> g
> 
> ```
> 
>
Assuming that for data `"a,b,c,d,,,,,e,f,g"` split should look like `a b c d , , e f g` you could find pair of comas and place some special mark between them. This way you will know that coma with that special mark after it need to be removed, but coma with special mark before it need to stay. Code based on that idea can look like

```
String data = "a,b,c,d,,,,,e,f,g";
data = data.replace(",,", ",XspecialSplitX,");

String[] tokens = data.split(",XspecialSplitX|(?<!XspecialSplitX),");
for (String s : tokens)
    System.out.print(s+" ");

```

Output: `a b c d , , e f g`

---

Faster and easier way without regex.  

If your string contains only **single** characters separated with comas then all wanted characters will have even indexes and separating comas odd. In this case all you need to do is iterate over all even indexes like this

```
char[] data="a,b,c,d,,,e,f,g".toCharArray();
for(int i=0; i<data.length; i+=2)
    System.out.println(data[i]);

```