Running a number of consecutive replacements on the same string

前端 未结 3 329
盖世英雄少女心
盖世英雄少女心 2021-01-12 08:43

I found this example for substring replacement:

use std::str;
let string = \"orange\";
let new_string = str::replace(string, \"or\", \"str\");
3条回答
  •  伪装坚强ぢ
    2021-01-12 09:35

    The regex engine can be used to do a single pass with multiple replacements of the string, though I would be surprised if this is actually more performant:

    extern crate regex;
    
    use regex::{Captures, Regex};
    
    fn main() {
        let re = Regex::new("(or|e)").unwrap();
        let string = "orange";
        let result = re.replace_all(string, |cap: &Captures| {
            match &cap[0] {
                "or" => "str",
                "e" => "er",
                _ => panic!("We should never get here"),
            }.to_string()
        });
        println!("{}", result);
    }
    

提交回复
热议问题