← 中文资源

简体中文版本

用 splitn 限段切分并保留余文

splitn 限制切分段数、最后一段保留未切的余文,rsplitn 从右侧切取末字段;与普通 split 的贪婪行为对照,解析带分隔符的消息不再碎裂。

阅读英文原文

实现说明

用 splitn 限段切分并保留余文可以归结为函数 main。

使用要点

  • 每一步打印都带着自己的标签:level=、message=、split all:。

常见问题

运行「用 splitn 限段切分并保留余文」会打印什么?

运行文件本身,level=、message=、split all: 这些前缀各对应一段演示逻辑。

核心语句

let none: Vec<&str> = line.splitn(0, ':').collect();
let greedy: Vec<&str> = line.split(':').collect();
let message = parts.next().unwrap_or("");

代码示例

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:?}");
}