我正在将复数形式移植到 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 named1a
and not the capture group at index1
. 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/