Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I replace a match with a variable in rust?

This piece of code replaces "World" with "London":

fn replace_with(foo: &str) -> String {
    use regex::Regex;
    let before = "Hello, World";
    let re = Regex::new(r"(.*?)(World)").unwrap();
    String::from(re.replace_all(before, "$1 London"))
}

I’d instead like to replace it with foo. How do I do that? I’ve tried using "$foo" or "${foo}" and that doesn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Two options:

format!("{} London", foo)`

In modern Rust (1.58+):

format!("{foo} London")

That’s the closest you can get to JavaScript template strings and the ${x} format.1

Where that’s the argument to your substitution, as in replace_all(before, format!(...)).

1 In Rust it’s more limited, you can’t get as adventurous with arrays and such, just simple variable names. {x[y]} is not a valid substitution, for example.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading