我尝试使用缩短的版本查找并替换字符串的所有实例,并且如果找到它,我想保留对捕获的引用。
我已经写了这段代码:
extern crate regex;
use regex::{Regex, Captures};
//... get buffer from stdin
let re = Regex::new(r"(capture something1) and (capture 2)").unwrap();
let out = re.replace_all(&buffer, |caps: &Captures| {
if let ref = caps.at(2).unwrap().to_owned() {
refs.push(ref.to_owned());
}
caps.at(1).unwrap().to_owned();
});
不幸的是,编译因错误而失败:
src/bin/remove_links.rs:16:18: 16:29 error: type mismatch resolving `for<'r, 'r> <[closure@src/bin/remove_links.rs:16:39: 22:6] as std::ops::FnOnce<(&'r regex::Captures<'r>,)>>::Output == std::string::String`:
expected (),
found struct `std::string::String` [E0271]
src/bin/remove_links.rs:16 let out = re.replace_all(&buffer, |caps: &Captures| {
^~~~~~~~~~~
src/bin/remove_links.rs:16:18: 16:29 help: run `rustc --explain E0271` to see a detailed explanation
src/bin/remove_links.rs:16:18: 16:29 note: required because of the requirements on the impl of `regex::Replacer` for `[closure@src/bin/remove_links.rs:16:39: 22:6]`
我无法理解它。我还尝试添加use regex::{Regex, Captures, Replacer}
,但这根本不会改变错误。
答案 0 :(得分:2)
正如@ BurntSushi5指出的那样,你的闭包应该返回一个String
。以下是未来参考的完整示例:
extern crate regex;
use regex::{Regex, Captures};
fn main() {
let buffer = "abcdef";
let re = Regex::new(r"(\w)bc(\w)").unwrap();
let out = re.replace_all(&buffer, |caps: &Captures| {
caps.at(1).unwrap().to_owned()
});
println!("{:?}", out); // => "aef"
}