regex - 无法获取 `Regex::replace()` 来替换编号的捕获组

标签 regex rust

我正在将复数形式移植到 Rust,但我在使用正则表达式时遇到了一些困难。我无法获得 Regex::replace() 方法来替换我期望的编号捕获组。例如,以下显示一个空字符串:

let re = Regex::new("(m|l)ouse").unwrap();
println!("{}", re.replace("mouse", "$1ice"));

我希望它像在 JavaScript(或 Swift、Python、C# 或 Go)中那样打印“mice”

var re = RegExp("(m|l)ouse")
console.log("mouse".replace(re, "$1ice"))

我应该使用一些方法来代替 Regex::replace() 吗?

检查 Inflector crate ,我看到它提取了第一个捕获组,然后将后缀附加到捕获的文本:

if let Some(c) = rule.captures(&non_plural_string) {
    if let Some(c) = c.get(1) {
        return format!("{}{}", c.as_str(), replace);
    }
}

但是,鉴于 replace 在我使用过正则表达式的所有其他语言中都有效,我希望它在 Rust 中也能正常工作。

最佳答案

the documentation 中所述:

The longest possible name is used. e.g., $1a looks up the capture group named 1a and not the capture group at index 1. To exert more precise control over the name, use braces, e.g., ${1}a.

Sometimes the replacement string requires use of curly braces to delineate a capture group replacement and surrounding literal text. For example, if we wanted to join two words together with an underscore:

let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap();
let result = re.replace("deep fried", "${first}_$second");
assert_eq!(result, "deep_fried");

Without the curly braces, the capture group name first_ would be used, and since it doesn't exist, it would be replaced with the empty string.

你想要re.replace("mouse", "${1}ice")

关于regex - 无法获取 `Regex::replace()` 来替换编号的捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332900/

相关文章:

windows - 如何将 Qt 与 Rust 一起使用?

java - 如何在除点以外的所有特殊字符处拆分字符串?

javascript - 这些正则表达式元字符之间有什么区别?

python - 按复合类名搜索时 BeautifulSoup 返回空列表

python - 在 Pandas 数据框上应用正则表达式函数

rust - 你如何借用 Rust 中的可变指针?

rust - 将 `self` 放入 Rust 中的 `Arc`

rust - 如何检查 Rust 1.1 中的路径是否存在?

rust - Rust:可变借款返回非可变借款

python - 如何在 Mac 上运行 redemo.py(或等效文件)?