← 中文资源

简体中文版本

用 match_indices 定位所有子串位置

match_indices 从左到右产出每个不重叠匹配的字节偏移与 &str 切片,借用自原文本;找不到时迭代器为空,遍历结束即返回。

阅读英文原文

实现说明

用 match_indices 定位所有子串位置可以归结为函数 main。 本示例的循环部分是 for (i, s) in log.match_indices("ERROR").take(2)。

使用要点

  • 直接运行文件,输出会带上标签,比如 error positions:、at byte、fatal positions:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「用 match_indices 定位所有子串位置」会打印什么?

运行文件本身,error positions:、at byte、fatal positions: 这些前缀各对应一段演示逻辑。

核心语句

let positions: Vec<usize> = log.match_indices("ERROR").map(|(i, _)| i).collect();
let none: Vec<usize> = log.match_indices("FATAL").map(|(i, _)| i).collect();
for (i, s) in log.match_indices("ERROR").take(2) {
    println!("at byte {i}: {s}");
}

代码示例

fn main() {
    let log = "ERROR disk full; ERROR retry; WARN stale; ERROR disk full";

    // 找出所有子串(substring)出现的位置(positions):
    // match_indices 从左到右产出每个不重叠匹配的字节偏移与切片
    let positions: Vec<usize> = log.match_indices("ERROR").map(|(i, _)| i).collect();
    println!("error positions: {positions:?}");

    // 第二个元素是借用自原文本的 &str,可以直接用
    for (i, s) in log.match_indices("ERROR").take(2) {
        println!("at byte {i}: {s}");
    }

    // 找不到时迭代器为空
    let none: Vec<usize> = log.match_indices("FATAL").map(|(i, _)| i).collect();
    println!("fatal positions: {none:?}");
}