How to select sample IDs using regular expressions

Drashti Shah
Bioinformatics with Rust
Dec 16, 2023
Generated with AI

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

--

--

Drashti Shah
Bioinformatics with Rust

ESG & climate data scientist by day. Aspiring computational biologist and game designer by night. A Rust fan who believes in an "open career".