How to split a string with multiple separators in Rust

1 Answer

0 votes
use regex::Regex;

/// Splits a string using multiple separators: comma, semicolon, pipe, dash, underscore
fn split_by_separators(input: &str, separators: &str) -> Vec<String> {
    let re = Regex::new(separators).unwrap();
    re.split(input)
        .map(|s| s.to_string())
        .collect()
}

fn main() {
    let input = "abc,defg;hijk|lmnop-qrst_uvwxyz";
    let separators = r"[,\;\|\-_]+";

    let words = split_by_separators(input, separators);

    for word in words {
        println!("{}", word);
    }
}


    
/*
run:

abc
defg
hijk
lmnop
qrst
uvwxyz
   
*/

 



answered Jul 21 by avibootz
...