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"
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023