How to select sample IDs using regular expressions
Published in
Dec 16, 2023
A Rust function that returns a vector of string slices that match a regex pattern
Arguments
- vector: a vector of string slices to be filtered
- pattern: a regex pattern to match the elements of the vector
Code & Example
use regex::Regex;
fn main() {
let bio_sample_id_vector = vec![
"SAMN12704278",
"SAMEA100981162",
"SAMN03738170",
"SAMN25236422",
"SAMN31210262",
"SAMD00036622",
];
let pattern = Regex::new(r"^SAMN.*2$").unwrap();
// Both the vector and the pattern are moved
// After the move, select_by_regex_pattern will own them
let selected_sample_ids = select_by_regex_pattern(bio_sample_id_vector, pattern);
println!("{:?}", selected_sample_ids)
}
fn select_by_regex_pattern(vector: Vec<&str>, pattern: Regex) -> Vec<&str> {
vector
.into_iter()
.filter(|&element| pattern.is_match(element))
.collect()
}
Next Steps
- Play with the code in Rust Playground
- Explore the regex crate