How to Use flat_map in Rust

Use flat_map in Rust to transform iterator items into zero or more new items and automatically flatten the result into a single stream.

Use flat_map to transform each item in an iterator into zero or more new items, automatically flattening the result into a single stream. It is ideal when you need to expand or filter elements during iteration without creating intermediate nested collections.

let lines: Vec<_> = input
    .lines()
    .flat_map(|line| {
        if line.starts_with("```") {
            Some(String::from("```"))
        } else {
            let result = regexen.iter().fold(line.to_string(), |result, regex| {
                regex.replace_all(&result, |caps: &Captures<'_>| {
                    caps.get(1).unwrap().as_str().to_string()
                }).to_string()
            });
            Some(result)
        }
    })
    .collect();