Adding all regex matches to vector

I have this code in function:

pub fn search_corrections(content: &str) {
        let regex_corrections = Regex::new("(\\[\\[)(.*?)(\\|)(.*?)(\\]\\])").unwrap();

        for found in regex_corrections.captures_iter(&content) {
            println!("{:#?}", found);
        }
}

I want to produce next vector at the end of function: first "layer" will be number of matches, like first match equalls vectored[0] etc. While second "layer" equals matches of regex. For example, this function's vectored[0][0] in this context:

fn main() {
    search_corrections("[[hello|world]]");
}

Should produce "[[hello|world]]", then vectored[0][1] would equal to "[[", etc.

How do i make this nested vector ???

I've came up with this solution:

pub fn search_corrections(content: &str) {
    let mut vector_match: Vec<Vec<&str>> = Vec::new();

    let regex_corrections = Regex::new("(\\[\\[)(.*?)(\\|)(.*?)(\\]\\])").unwrap();

    for found in regex_corrections.captures_iter(&content) {
        let mut vector_temp: Vec<&str> = Vec::new();

        for i in 0..6 {
            vector_temp.push(found.get(i).unwrap().as_str());
        }

        vector_match.push(vector_temp);
    }

    println!("{:#?}", vector_match);
}
use regex::Regex;
use once_cell::sync::Lazy;
pub fn search_corrections(content: &str) {
    static REGEX_CORRECTIONS: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(\[\[)(.*?)(\|)(.*?)(\]\])").unwrap());

    let vector_match: Vec<Vec<&str>> = REGEX_CORRECTIONS
        .captures_iter(content)
        .map(|c| c.iter().map(|m| m.unwrap().as_str()).collect())
        .collect();

    println!("{:#?}", vector_match);
}

(playground)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.