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"

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

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