String.splitWithDelimiters Keeps Separators
Split text with JDK 21 String.splitWithDelimiters so matched separators stay in odd array slots, comparing positive, zero, and negative limit rules.
Code
import java.util.Arrays;
public class DelimiterTokenSplit {
public static void main(String[] args) {
String expr = "10+20-30*40";
// Even slots hold tokens; odd slots preserve each matched operator separator
String[] all = expr.splitWithDelimiters("[+*/-]", 0);
System.out.println("tokens+delims: " + Arrays.toString(all));
// limit=3 stops after 2 delimiters (3 token slots), keeping the remaining suffix
String[] capped = expr.splitWithDelimiters("[+*/-]", 3);
System.out.println("limit=3 capped: " + Arrays.toString(capped));
// Trailing separator: limit=0 drops the final empty token but retains the delimiter
String trailing = "a+b+";
System.out.println("limit=0 tail: " + Arrays.toString(trailing.splitWithDelimiters("\\+", 0)));
System.out.println("limit=-1 tail: " + Arrays.toString(trailing.splitWithDelimiters("\\+", -1)));
// Contrast with String.split, which discards every matched separator
System.out.println("plain split: " + Arrays.toString(expr.split("[+*/-]")));
}
}Inside the routine — String.splitWithDelimiters Keeps Separators
Under the hood: the class DelimiterTokenSplit and the function main.
Points of care
- Uses solely built-in runtime APIs, removing external package supply-chain review overhead.
Using it
Primary invocation prototype opens as public static void main(String[] args)
The file’s steps show up in the output as tokens+delims:, limit=3 capped:, limit=0 tail:.
Key statements
String[] capped = expr.splitWithDelimiters("[+*/-]", 3);
String[] all = expr.splitWithDelimiters("[+*/-]", 0);
String expr = "10+20-30*40";
Interactive Tools for This Topic
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.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
FAQ
- What does String.splitWithDelimiters Keeps Separators print when run?
- Running the file directly is enough — expect labeled output lines such as `tokens+delims:`, `limit=3 capped:`, `limit=0 tail:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.