Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

In Rust, how to do replace_all( regex, Rep ) of Regex when Rep contains some variable?

This is about Rust, regex::Regex.

For the following my code, I tried to output the input word followed by a random string.

Playground

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.

Could you give me how to fix my code?

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`
question from:https://stackoverflow.com/questions/65855968/in-rust-how-to-do-replace-all-regex-rep-of-regex-when-rep-contains-some-var

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...