How do I split-up string using regular expression?

This example uses the java.util.regex.Pattern class’s 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.println("Colour = "" + colour + """);


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply