expression

Regex::replace and replace_all

Replace the first match or every nonoverlapping match. These operations return a Cow string so an unchanged result can borrow input. This example uses the external regex crate; see the staged Cargo manifest. Expected stdout (not executed): a# b2 a# b# Common mistake: Expecting replace to change every occurrence.

Formal Syntax & Structure

rust syntaxrust
re.replace(text, replacement); re.replace_all(text, replacement)

Working Example

Example Snippetrust
fn main() {    let re = regex::Regex::new(r"[0-9]+").unwrap();    println!("{}", re.replace("a1 b2", "#"));    println!("{}", re.replace_all("a1 b2", "#"));}
Rust Reference