Find Substring Positions With match_indices

Locate every occurrence of a substring with match_indices, which yields byte offsets and matched &str slices, and yields nothing at all when nothing matches.

RustData Integrity

Code

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

What the code does

Count the function main as the entire surface area of Find Substring Positions With match_indices.

The cycling part of this snippet is for (i, s) in log.match_indices("ERROR").take(2).

Applying it

Running the file prints labeled results such as error positions:, at byte, fatal positions: — each operation’s effect is visible in the output.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does Find Substring Positions With match_indices print when run?
Execute the whole file; each printed line is prefixed with a label like `error positions:`, `at byte`, `fatal positions:`.