I'm new to rust and I'm having a hard time wrapping my head around ownership concepts. I have a string that has substrings with a specific pattern inside of it, like "alice [bob] charlie [dave]", and I'm trying to get to a vector of strings that looks like ("john","dave"). My first go was at using a regex with non capturing groups, but I can't get that to work, because I don't really understand rust very well:
let re = Regex::new(r"(?:\[)([a-zA-Z]+)(?:])").unwrap();
let mut answer: Vec<&str> = re.captures_iter((&text)).map(|capGroup| &*String::from(&capGroup[1])).collect();
But I could collect them like so:
let re = Regex::new(r"\[[a-zA-Z0-9_]+]").unwrap();
let mut answer: Vec<&str> = re.find_iter((&text)).map(|mtc| mtc.as_str()).collect();
The problem with this, is that it leaves me with ("[bob]","[dave]"), and I've also been unsucessuful at trimming the first and last few characters of the string. As a matter of fact, I don't even understand how iterating works here it seems, because when I try to do:
let mut it = answer.iter();
for name in &mut it{
...
I end up with name being of type &&str
instead of the &str
that I expected.
So my questions would be:
- How do I use capture groups in rust for what I'm trying to do in the first example, in an idiomatic fashion? I feel like I'm close to the mark of applying something to all the captures and collecting into a vec but something is escaping me.
- Given
Vec<&str>
, how do I modify the strings inside it? What is it that I'm missing here? - Why is my iteration item of type
&&str
when I do that? - Is there a better way overall of achieving this in rust?