Hi all. This request for review is less about the regex parts (I already know there's problems, e.g. I'm not escaping regex characters) and more about how I've gone about doing it in Rust. I would like to understand how I can turn this into more idiomatic rust code.
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
fn extract_tokens(input: &str, pattern: &str) -> HashMap<String, String> {
let mut pattern_str = String::from(pattern);
let token_re = Regex::new(r"\{(.*?)\}").unwrap();
for cap in token_re.captures_iter(pattern) {
let cap = String::from(&cap[0]);
let repl = &format!("(?P<{}>.+)", &cap[1..cap.len()-1]);
pattern_str = pattern_str.replace(&cap, repl);
}
let mut out = HashMap::new();
let group_re = Regex::new(&pattern_str).unwrap();
for group in group_re.captures_iter(input) {
for name in group_re.capture_names() {
match name {
Some(n) => {
out.insert(
String::from(n),
String::from(group.name(n).unwrap().as_str()),
);
}
None => {}
}
}
}
out
}
fn main() {
println!(
"{:?}",
extract_tokens(
"My name is Inigo Montoya",
"My name is {first_name} {last_name}"
)
);
}
// outputs: {"last_name": "Montoya", "first_name": "Inigo"}