Split With A Limit And Keep The Remainder
Bound how many pieces splitn produces so the final piece keeps the untouched remainder, and use rsplitn to slice from the right edge instead.
Code
fn main() {
// message format: level:module:message, and message itself may contain colons
let line = "WARN:auth:token expired: please relogin";
// splitn(3, ':'): at most 3 pieces, and everything past the limit stays verbatim (the remainder)
let mut parts = line.splitn(3, ':');
let level = parts.next().unwrap_or("");
let module = parts.next().unwrap_or("");
let message = parts.next().unwrap_or("");
println!("level={level} module={module}");
println!("message={message}");
// a plain split would shred message too; the contrast shows what the limit buys
let greedy: Vec<&str> = line.split(':').collect();
println!("split all: {greedy:?}");
// rsplitn cuts from the right: take the last field first and keep the rest as one piece
let mut tail = line.rsplitn(2, ':');
let last = tail.next().unwrap_or("");
let rest = tail.next().unwrap_or("");
println!("rest={rest}");
println!("last={last}");
// with limit 0, splitn yields nothing at all
let none: Vec<&str> = line.splitn(0, ':').collect();
println!("limit 0: {none:?}");
}How it works
main is the only function; the demo is the splitn call itself.
Applying it
Running the file prints labeled results such as level=, message=, split all: — the limited split keeps the remainder intact in the message= line.
Statements that matter
let none: Vec<&str> = line.splitn(0, ':').collect();
let greedy: Vec<&str> = line.split(':').collect();
let message = parts.next().unwrap_or("");
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does Split With A Limit And Keep The Remainder print when run?
- No setup needed: run the file and look for labeled lines like `level=`, `message=`, `split all:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.