代码之家  ›  专栏  ›  技术社区  ›  AbhiNickz

如何将regex replace中捕获的模式转换为大写?

  •  2
  • AbhiNickz  · 技术社区  · 6 年前

    我想替换 /test/test1 具有 TEST1: .这就是我的出发点:

    extern crate regex; // 1.0.1
    
    use regex::Regex;
    
    fn main() {
        let regex_path_without_dot = Regex::new(r#"/test/(\w+)/"#).unwrap();
    
        let input = "/test/test1/test2/";
    
        // Results in "test1:test2/"
        let result = regex_path_without_dot.replace_all(input, "$1:");
    }
    

    我试过用

    let result = regex_path_without_dot.replace_all(&input, "$1:".to_uppercase());
    

    但我有个错误:

    error[E0277]: the trait bound `for<'r, 's> std::string::String: std::ops::FnMut<(&'r regex::Captures<'s>,)>` is not satisfied
      --> src/main.rs:10:41
       |
    10 |     let result = regex_path_without_dot.replace_all(&input, "$1:".to_uppercase());
       |                                         ^^^^^^^^^^^ the trait `for<'r, 's> std::ops::FnMut<(&'r regex::Captures<'s>,)>` is not implemented for `std::string::String`
       |
       = note: required because of the requirements on the impl of `regex::Replacer` for `std::string::String`
    

    我如何实现这一要求的特质?有什么简单的方法可以做到这一点吗?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Shepmaster Tim Diekmann    6 年前

    Regex::replace 有签名

    pub fn replace<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Cow<'t, str>
    

    Replacer 执行人:

    • &'a str
    • ReplacerRef<'a, R> where R: Replacer
    • F where F: FnMut(&Captures) -> T, T: AsRef<str>
    • NoExpand<'t>

    没有实现 String ,这是错误消息的直接原因。您可以通过转换 字符串 在字符串切片中:

    replace_all(&input, &*"$1:".to_uppercase()
    

    由于大写版本与小写版本相同,因此不会有任何更改。

    但是,执行 替代品 以结束 有用的:

    let result = regex_path_without_dot.replace_all(&input, |captures: &regex::Captures| {
        captures[1].to_uppercase() + ":"
    });
    

    replace_all(&input, "$1:".to_uppercase())
    

    这显示了在理解此功能如何工作或在函数优先级方面的一个基本错误。这和说:

    let x = "$1:".to_uppercase();
    replace_all(&input, x)
    

    或者,同样地,因为 1 是大写的吗 1个 $ 是大写的吗 $ 以下内容:

    let x = String::from("$1:");
    replace_all(&input, x)
    

    调用类似于 to_uppercase 不会神奇地推迟到“晚些时候”。