Programming Tips - Java: How to use String.split()

Date: 2026mar28 Language: Java Q. Java: How to use String.split() A. Unsurprisingly this method breaks a String to an array. Be aware that it uses a regular expression to decide where to split. This is powerful but also slightly inconvenient for simple cases. If the split regex is anything but trivial or there are many String.splits()'s I prefer Pattern.split() so I can use a compiled pattern (for speed). Three full examples are below: Example 1
// Example 1: Splitting on simple regex class Demo { public static void main(String args[]) { String things = "one:two:three"; var a = things.split(":"); // A single character is a valid regex for (String thing : a) { System.out.println("thing=" + thing); } } }
Output:
thing=one thing=two thing=three
Example 2
// Example 2: Slightly complicated regex // NOT WHAT I WOULD DO. Use a compiled Pattern instead class Demo { public static void main(String args[]) { String things = "one two\tthree"; // Regex matches one or more space-like chars var a = things.split("\\s+"); // SLOW for (String thing : a) { System.out.println("thing=" + thing); } } }
Output:
thing=one thing=two thing=three
Example 3
// Example 3: Slightly complicated regex so we use a compiled Pattern // THIS IS WHAT I WOULD DO import java.util.regex.Pattern; class Demo { private static final Pattern mSpacesPattern = Pattern.compile("\\s+"); public static void main(String args[]) { String things = "one two\tthree"; var a = mSpacesPattern.split(things); for (String thing : a) { System.out.println("thing=" + thing); } } }
Output:
thing=one thing=two thing=three