let mut my_cap: &str;
let re = Regex::new(r"some words").unwrap();
for cap in re.captures_iter(s) {
my_cap = &cap[1];
}
println!("{}", my_cap);
error : borrowed value does not live long enough
how to fix this error?
let mut my_cap: &str;
let re = Regex::new(r"some words").unwrap();
for cap in re.captures_iter(s) {
my_cap = &cap[1];
}
println!("{}", my_cap);
error : borrowed value does not live long enough
how to fix this error?
You have to store the my_cap as String - ie, own the string. So. my_cap = String::from(&cap[1]);.
If you want the last one :
let cap = re.captures_iter(s).last().map(|c| c[1].to_owned());
If you don’t need to store the &str long-term, (longer than how long the string the regex was run on can stay borrowed), you can use the Captures::get method and the Match::as_str method to get a &str with longer lifetime than what the Index syntax supports. I.e. instead of &cap[1], use cap.get(1).unwrap().as_str().
Note that your regex only has a single group, so indexing at [1] will fail anyway. But something like
let re = Regex::new(r"some words").unwrap();
let mut my_cap: &str = ""; // needs to be initialized because the loop
// below might not run at all
for cap in re.captures_iter(s) {
my_cap = cap.get(0).unwrap().as_str();
}
println!("{}", my_cap);
would work.
It worked! Thanks.