String Split Regex Pitfalls
String.split treats its argument as a regex: dots swallow whole strings, trailing empties vanish by default, and a negative limit is what preserves them.
Code
import java.util.Arrays;
import java.util.regex.Pattern;
public class TagParser {
public static void main(String[] args) {
String tags = "java,sql,,bash";
// Trailing empty strings are dropped by default: adding a trailing comma changes nothing
System.out.println("plain: " + Arrays.toString(tags.split(",")));
System.out.println("trailing cut: " + Arrays.toString((tags + ",").split(",")));
// Negative limit: trailing empty strings are kept
System.out.println("limit -1: " + Arrays.toString((tags + ",").split(",", -1)));
// The argument is a regex: '.' is a metacharacter that swallows the whole string into empties
String ip = "10.0.0.7";
System.out.println("dot as regex: " + ip.split(".").length);
// Pattern.quote turns literal text into a safe regex
System.out.println("quoted dot: " + Arrays.toString(ip.split(Pattern.quote("."))));
}
}How it works
String Split Regex Pitfalls keeps everything in the class TagParser and the function main.
Applying it
The demo output is labeled (plain:, trailing cut:, limit -1:), so every printed line maps back to its originating operation.
Statements that matter
String tags = "java,sql,,bash";
String ip = "10.0.0.7";
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.
FAQ
- What does String Split Regex Pitfalls print when run?
- The script runs standalone; its 5 labeled outputs include `plain:`, `trailing cut:`, `limit -1:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.