java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.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 + """);
        }
    }
}