Java String.split and Pattern.quote
A delivery record may contain an order code, a quantity, and a blank note. Split on the literal separator and keep the final empty field when its position matters.
A simple example
String.split and Pattern.quote
- Start with a,b
- Do this Split at the comma
- Result a and b
class Main {
public static void main(String[] args) throws Exception {
System.out.println(java.util.Arrays.toString("a,b".split(",")));
}
}
[a, b]
Syntax
text.split(Pattern.quote(delimiter), -1)
JDK 21 method signatures (2)
public String[] split(String regex, int limit)
public String[] split(String regex)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSplit literal pipe-delimited records
An import uses punctuation to separate fields, but a field's own value may also contain punctuation. Choose the literal separator and the split limit deliberately so the remaining text keeps its intended meaning.
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) throws Exception {
String[] columns = "A|7|".split(Pattern.quote("|"), -1);
System.out.println(columns.length);
System.out.println("[" + columns[2] + "]");
}
}
3 []
A pipe has special meaning in a regex. Quoting it and retaining the final empty column lets the caller distinguish a missing value from a missing column.
Keep the blank final cell of a timetable
A timetable or route import divides each record at separators. Test the behavior at an empty field so later columns do not shift when the writer leaves a value blank.
class Main {
public static void main(String[] args) throws Exception {
String row = "09:00|Math|";
System.out.println(java.util.Arrays.toString(row.split("\\|", -1)));
}
}
[09:00, Math, ]
The negative limit preserves the missing room as a third field.
Keep the complete note after a setting name
A configuration value can itself contain the character that separates the name from the value. Limit the split so the complete note after the first separator reaches the consuming application.
class Main {
public static void main(String[] args) throws Exception {
String option = "note=bring=a=pen";
System.out.println(java.util.Arrays.toString(option.split("=", 2)));
}
}
[note, bring=a=pen]
A limit of two stops splitting after the first equals sign.
What to watch for
String.split takes a regular expression. Pattern.quote treats a separator such as a pipe as literal text.