4
0
0

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"}, "Hello\t,World".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello,\rWorld".split(REGEX)));
        Assert.assertTrue(Arrays.equals(new String []{"Hello", "World"}, "Hello\t ,\r\nWorld".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 lo\t, ,\rWorld".split(REGEX)));
    }
}


Einsortiert unter:Java Basics Tagged: comma-separated, java, regex, split, String, whitespace
Discussion

-