Java — Parsing strings with a split limit
Java String.split accepts a limit. A limit of two preserves any later separators in the second field, so a setting can contain an equals sign in its value.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
class Main {
public static void main(String[] args) throws Exception {
String[] parts = "a=b".split("=");
System.out.println(parts[1]);
}
}
b
Split one setting into a key and a value
String.split treats its first argument as a regular expression. An equals sign matches literally here. A limit of two preserves further separators in the value, and strip removes surrounding whitespace.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
Java 17 or later. Run these commands from the directory containing the example.
java Main.java
class Main {
public static void main(String[] args) {
String[] parts = " city = Lima ".split("=", 2);
if (parts.length == 2) {
System.out.println(parts[0].strip() + "=" + parts[1].strip());
}
}
}
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.