无法获取`Regex::replace()` 来替换编号的捕获组 [英] Cannot get `Regex::replace()` to replace a numbered capture group

查看:38
本文介绍了无法获取`Regex::replace()` 来替换编号的捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm porting a pluralizer to Rust and I'm having some difficulty with regular expressions. I can't get the Regex::replace() method to replace a numbered capture group as I would expect. For example, the following displays an empty string:

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

我希望它像在 JavaScript(或 Swift、Python、C# 或 Go)中那样打印老鼠"

I would expect it to print "mice", as it does in JavaScript (or Swift, Python, C# or Go)

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

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

Is there some method I should be using instead of Regex::replace()?

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

Examining the Inflector crate, I see that it extracts the first capture group and then appends the suffix to the captured text:

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

然而,鉴于 replace 在我使用过正则表达式的所有其他语言中都可以使用,我希望它也可以在 Rust 中使用.

However, given that replace works in every other language I've used regular expressions in, I would expect it work in Rust as well.

推荐答案

文档:

使用可能的最长名称.例如,$1a 查找名为 1a 的捕获组,而不是索引 1 处的捕获组.要对名称进行更精确的控制,请使用大括号,例如 ${1}a.

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

如果没有大括号,将使用捕获组名称 first_,由于它不存在,它将被替换为空字符串.

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::replace()` 来替换编号的捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆