How do I split-up string using regular expression?

This example uses the java.util.regex.Pattern.split() method to split-up input string separated by commas or whitespaces.

package org.kodejava.example.regex;

import java.util.regex.Pattern;

public class RegexSplitExample {
    public static void main(String[] args) {
        // Pattern for finding commas, whitespaces (space, tabs, new line,
        // carriage return, form feed).
        String pattern = "[,\\s]+";
        String colours = "Red,White, Blue   Green        Yellow, Orange";

        Pattern splitter = Pattern.compile(pattern);
        String[] result = splitter.split(colours);

        for (String colour : result) {
            System.out.format("Colour = \"%s\"%n", colour);

The result of our code snippet is:

Colour = "Red"
Colour = "White"
Colour = "Blue"
Colour = "Green"
Colour = "Yellow"
Colour = "Orange"

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.