To replace all occurrences of a substring in a string using regular expression in Rust, you can use the regex
crate.
In this example,
regex
crate to the dependencies in Cargo.toml
.regex::Regex
struct to create a regular expression pattern matching "Hello".replace_all
method to replace all occurrences of the pattern with "Hi".[dependencies]
regex = "1.5.4"
fn main() {
let str = "Hello World Hello";
let re = regex::Regex::new("Hello").unwrap();
let new_str = re.replace_all(str, "Hi");
println!("{}", new_str);
}
Hi World Hi
In this example,
regex
crate to the dependencies in Cargo.toml
.regex::Regex
struct to create a regular expression pattern matching digits (\d).replace_all
method to replace all occurrences of the pattern with 'Y'.[dependencies]
regex = "1.5.4"
fn main() {
let str = "Hello123World789";
let re = regex::Regex::new(r"\d").unwrap();
let new_str = re.replace_all(str, "Y");
println!("{}", new_str);
}
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in Rust language with well detailed examples.