1

I'm trying to find and replace all instances of a string with a shortened version, and I want to maintain references to a capture if it's found.

I've written this code:

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();
});

Unfortunately compilation fails with the error:

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]`

I can't make sense of it. I've also tried adding use regex::{Regex, Captures, Replacer} but that doesn't change the error at all.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ray
  • 1,966
  • 4
  • 24
  • 39
  • 3
    Your closure returns a `()` since the last expression is terminated by a semicolon, but the closure must return a `String`. Try removing the semicolon. – BurntSushi5 Aug 25 '16 at 01:56

1 Answers1

2

As @BurntSushi5 pointed out, your closure should return a String. Here is a complete example for future reference:

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"
}
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127