This code snippet uses the java.util.regex.Pattern.split()
method to split-up input string separated by commas or whitespaces (spaces, tabs, new lines, carriage returns, form feeds).
package org.kodejava.regex;
import java.util.regex.Pattern;
public class RegexSplitExample {
public static void main(String[] args) {
// Pattern for finding commas, whitespaces (spaces, tabs, new lines,
// carriage returns, form feeds).
String pattern = "[,\\s]+";
String colors = """
Red,White, Blue Green Yellow,
Orange Pink""";
Pattern splitter = Pattern.compile(pattern);
String[] results = splitter.split(colors);
for (String color : results) {
System.out.format("Color = \"%s\"%n", color);
}
}
}
The result of our code snippet is:
Color = "Red"
Color = "White"
Color = "Blue"
Color = "Green"
Color = "Yellow"
Color = "Orange"
Color = "Pink"