Closed
Description
I'm trying to write something like the following:
struct MyReplacer;
impl Replacer for MyReplacer {
fn reg_replace(&mut self, caps: ®ex::Captures) -> Cow<str> {
let cap: &str = caps.at(1).unwrap();
Cow::Borrowed(cap)
}
}
fn main() {
let re = regex::Regex::new("foo(.*)bar").unwrap();
let my_data = "foocatsbar";
let result = re.replace_all(my_data, MyReplacer);
}
But I'm running into the following lifetime error:
src/lib.rs:11:30: 11:35 error: cannot infer an appropriate lifetime for lifetime parameter `'t` due to conflicting requirements [E0495]
src/lib.rs:11 let cap: &str = caps.at(1).unwrap();
^~~~~
There are some suggestions about adding explicit lifetime parameters, but it seems like nothing I tried compiled.
What I'm trying to do is replace some parts of a String, but it's not possible to write a regex that will exactly represent what I want. So in my MyReplacer
, I want to extract the capture group, and based on the value of the capture group, either build a new string to return as a Cow::Owned(String)
, or return the capture group as Cow::Borrowed(&str)
as to avoid an allocation.
Do you have any hints about how to do this? I'm on rust nightly (1.7)
Thanks!