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.
CodePudding user response:
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.