Created
April 20, 2021 13:37
-
-
Save Bas-Man/8a10393bb9d7c40e5413c460485e2075 to your computer and use it in GitHub Desktop.
Applying multiple regex patterns against a string to see which one matches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use regex::{Regex, RegexSet}; | |
fn main() { | |
let string1 = "a:test"; | |
let string2 = "a/24"; | |
let string3 = "a"; | |
let string4 = "a:test/24"; | |
// Create a RegexSet | |
let regex_set = RegexSet::new(&[r"(a$)", r"a:(.*)", r"a(/\d{1,2})"]).unwrap(); | |
println!( | |
"1: {}", | |
get_match(®ex_set, string1).unwrap_or("failed1".to_string()) | |
); | |
println!( | |
"2: {}", | |
get_match(®ex_set, string2).unwrap_or("failed2".to_string()) | |
); | |
println!( | |
"3: {}", | |
get_match(®ex_set, string3).unwrap_or("failed3".to_string()) | |
); | |
println!( | |
"4: {}", | |
get_match(®ex_set, string4).unwrap_or("failed4".to_string()) | |
); | |
} | |
fn get_match(regex_set: &RegexSet, string: &str) -> Option<String> { | |
let mut result = None; | |
// Check if there is no match, return None if this is true | |
if !regex_set.is_match(string) { | |
return result; | |
} else { | |
// There was a match so do the work of finding the match | |
let matched = regex_set.matches(string); | |
// Find the index of the regular expreess that matched. | |
let idx: usize = matched.iter().next().unwrap(); | |
// Get the matching pattern from the RegexSet | |
let pat = regex_set.patterns(); | |
// Create a New Regex using the previous matched pattern. | |
let re = Regex::new(&pat[idx]).unwrap(); | |
// Find the captured string. THere should only be one. | |
for cap in re.captures(string) { | |
result = Some(cap[1].to_string()); | |
break; | |
} | |
}; | |
result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment