Split comma-separated Strings in Java

Shortly, I saw some code like this to work with comma separated lists:

String [] elements = "Hello, World".split(",");
for (String element : elements) {
    String trimmedElement = element.trim();
    // do something with trimmedElement
}

The code uses String.split(“,”) to split the strings at commas and String.trim() to remove unwanted whitespaces.

But theres’s a much more elegant way to do that in one step: Regexes. Fortunately, String.split(“,”) directly supports these. A simple Regex to ignore all spaces around the comma would look like this: ” *, . To support other whitespaces, this can be changed to: “\s,\s*”. Some testcases for this:

public class CommaSeparatedStringTest {
    public static final String REGEX = "\s*,\s*";
    @Test
    public void testSplit() {
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello,World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello, World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello ,World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello , World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hel lo", "World"}, "Hel lo,World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hellot,World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello,rWorld".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hellot ,rnWorld".split(REGEX)));
    }
}

But there’s more possible … If you even want to remove empty elements/double commas (e.g. “Hello,,World”), you can use the following Regex: “[\s],[,\s]. Again some testcases for this Regex:

public class CommaSeparatedStringTest {
    public static final String REGEX = "\s*,[,\s]*";
    @Test
    public void testSplit() {
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello,,World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello, ,World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hel lo", "World"}, "Hel lot, ,rWorld".split(REGEX)));
    }
}
Short URL for this post: http://blog.oio.de/GrN6a
This entry was posted in Java Basics and tagged , , , , , . Bookmark the permalink.

One Response to Split comma-separated Strings in Java

  1. Sharan says:

    Thanks for the tip! Was of great help!

Leave a Reply