regexrustpattern-matching

How to match a string to multiple strings while capturing the result of a capture in Rust


new to Rust here and was trying to follow some of the exercises form the documentation and out of curiosity, wondering what is the 'best' way to achieve the following:

Given a list of regex, how can I:

  1. know which regex it is matching
  2. what are the capture groups, without having to match the regex a second time

Example code of what I was trying:

use regex::Regex;

let pattern1: Regex = Regex::new(r"^(add|Add) ([a-zA-Z]*) to ([a-zA-Z]*)")
let pattern2: Regex = Regex::new(r"^(list|List) all$")

let text = String::from("add employee to company");

match text {
    if pattern1.is_match(&text) => do_something_with(<captured_group>),
    if pattern2.is_match(&text) => do_something_else_with(),
    _ => ()
}

I was expecting that this code somehow could call do_something_with with the pattern matched and be able to extract employee and company. I could maybe call captures for the regex within the function, but I would be parsing the regex twice


Solution

  • Regex::captures returns None if no match is found, so you don't need to check using is_match. As cafce25 commented, you can simply use if let on pattern.captures(&text) as follows:

    use regex::Regex;
    
    fn main() {
        let pattern1: Regex = Regex::new(r"^add|Add ([a-zA-Z]*) to ([a-zA-Z]*)").unwrap();
        let pattern2: Regex = Regex::new(r"^list|List all$").unwrap();
    
        let text = String::from("add employee to company");
    
        if let Some(captures) = pattern1.captures(&text) {
            // do_something_with(captures);
        } else if let Some(captures) = pattern2.captures(&text) {
            // do_something_else_with(captures);
        }
    }
    

    You could also use a nested match on both of the pattern.captures(&text), but that would be less concise.