rust - 在同一个字符串上运行多个连续替换

标签 rust

我找到了这个子字符串替换的例子:

use std::str;
let string = "orange";
let new_string = str::replace(string, "or", "str");

如果我想在同一个字符串上运行多个连续替换,出于清理目的,我该如何在不为每个替换分配新变量的情况下执行此操作?

如果您要编写地道的 Rust,您将如何编写多个链式子字符串替换?

最佳答案

regex engine可用于对字符串进行多次替换,但如果这实际上性能更高,我会感到惊讶:

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

关于rust - 在同一个字符串上运行多个连续替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476895/

相关文章:

rust - 如何在 Rust 中使用 From trait 实现双向转换?

json - 无法从 serde 导出和使用特征反序列化

rust - 错误 : could not compile `time` when using cargo to compile

loops - 为什么我不能在两个不同的映射函数中可变地借用变量?

rust - 如何追加到现有的Apache箭头数组

rust - 为什么我的 Future 实现一开始就陷入困境?

rust - 如何将借用的内容移至关闭连接

rust - 从文件反序列化Toml时出现无用的错误

vector - 获取存储在 n 维向量中的元素数

android - 如何将 Flutter 应用程序的构建过程与 Rust 代码集成?即在构建 Flutter 代码时,如何自动构建其 Rust 代码?