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.

RustConfig Management

Code

rustsnippet
27 lines
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

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.