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 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019