9951 explained code solutions for 126 technologies


rustHow to replace all using regex in Rust?


Regex in Rust can be used to replace all occurrences of a pattern in a string. To do this, the replace_all method can be used.

let s = "Hello, world!";
let replaced = s.replace_all("world", "Rust");
println!("{}", replaced);

Output example

Hello, Rust!

The replace_all method takes two parameters: a pattern and a replacement string. The pattern is a regular expression, and the replacement string is the string that will be used to replace all occurrences of the pattern.

Code explanation

  • let s = "Hello, world!";: This line declares a variable s and assigns it the value "Hello, world!".
  • let replaced = s.replace_all("world", "Rust");: This line calls the replace_all method on the s variable, passing in the pattern "world" and the replacement string "Rust".
  • println!("{}", replaced);: This line prints the value of the replaced variable, which is the result of the replace_all method.

Helpful links

Edit this code on GitHub