Cannot get `Regex :: replace ()` to replace a numbered capture group

I am porting a pluralizer to Rust and am having difficulty with regexes. I can't seem to get the method Regex::replace()

to replace the numbered capture group as I expected. For example, the following line displays an empty line:

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

      

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

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

      

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

?

Examining the Inflector drawer , I can see that it extracts the first capture group and then adds a 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);
    }
}

      

However, given that it replace

works in any other language I've used regular expressions, I expect it to work in Rust as well.

+3


source to share


1 answer


As the documentation states :

The longest name is used. for example, $1a

looks at a named 1a

capture group rather than an indexed capture group 1

. To control the name more precisely, use curly braces, for example ${1}a

.

and



Sometimes string replacement requires the use of curly braces to distinguish between the capturing group replacement and the surrounding literal. For example, if we want to combine 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 capturing group name first_

will be used, and since it does not exist, it will be replaced with an empty string.

Do you want to re.replace("mouse", "${1}ice")

+5


source







All Articles