How do I call Regex::replace_all when the replacer uses a variable?

Viewed 308

For the following my code, I tried to output the input word followed by a random string. The first function compiles but I don't want it because it does not use the random string. The second function yields a compiler errors.

How do I fix it?

use regex::Regex;

fn main() {
    let cd="rust";
    ok_but_i_dont_want_it(cd);
    compiler_err(cd);
}

fn ok_but_i_dont_want_it(cd:&str){
    let random_str="j93bg8";
    let reg_idnt=Regex::new(r"(?P<ident>[_A-Za-z]{1,}[_A-Za-z0-9]{0,})").unwrap();
    let cd=reg_idnt.replace_all(" rust ","${ident}_{}");
    println!("{}",cd);
}

fn compiler_err(cd:&str){
    let random_str="j93bg8";
    let reg_idnt=Regex::new(r"(?P<ident>[_A-Za-z]{1,}[_A-Za-z0-9]{0,})").unwrap();
    let cd=reg_idnt.replace_all(cd,format!("${ident}_{}",random_str));
    println!("{}",cd);
}
error: there is no argument named `ident`
  --> src/main.rs:18:47
   |
18 |      let cd=reg_idnt.replace_all(cd,format!("${ident}_{}",random_str));
   |                                               ^^^^^^^

error[E0277]: expected a `FnMut<(&regex::Captures<'_>,)>` closure, found `String`

Playground

1 Answers

If you don't want format! to handle the {ident}, you can escape it by doubling up the braces:

reg_idnt.replace_all(cd, format!("${{ident}}_{}", random_str));

This will cause format! to ignore it and the result will be "{ident}_j93bg8" which is passed to replace_all.


You're missing an .as_str() to pass the String from format! as a &str to satisfy Replacer.

format!("${{ident}}_{}", random_str).as_str()

See it running on the playground

Related