Reputation: 59
I have to replace certain parts in a text file but do not exactly how to manage this. Given the text:
Hello adorable world! Hello fantastic world! Hello my miserable world! Goodbye my adorable world! Goodbye my fantastic world! Goodbye my miserable world!
Now I am searching for the word following the "Hello my" and have to replace it by the next word in a given list - let's take "crucial" here
let mut my_text = "... see above";
let my_reg = Regex::new(r"Hello my (\S+) world!").unwrap();
let caps = my_reg.captures(&my_text).unwrap();
my_text = my_reg.replace(&my_text, "crucial".to_string()).to_string();
but this will - not unexpected - replace "Hello my miserable world!" completely with "crucial"
What do I have to do to replace only the caps.get(1) - which here is the word "miserable"?
Upvotes: 1
Views: 958
Reputation: 58735
As you discovered, Regex::replace
replaces the entire match. You can however, include parts of the match in the replacement.
To do that, you need to switch around which parts of the expression are capturing, so you can refer to the parts you want to keep instead of the parts you want to throw away:
let my_text = "Hello my miserable world!".to_string();
let my_reg = Regex::new(r"(Hello my) \S+ (world!)").unwrap();
let caps = my_reg.captures(&my_text).unwrap();
let my_text = my_reg.replace(&my_text, "$1 crucial $2".to_string()).to_string();
println!(my_text); // "Hello my crucial world!"
Upvotes: 4