Regex



examples/regex/regex-substitute/Cargo.toml
[package]
name = "regex-substitute"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
regex = "1.9.3"

examples/regex/regex-substitute/src/main.rs
use regex::Captures;
use regex::Regex;

fn main() {
    let text = "The black cat climbed the green tree";
    println!("'{}'", &text);

    let re = Regex::new(r"cat").unwrap();
    let result = re.replace_all(text, "dog");
    println!("'{}'", &result);

    // We can use the captured substring by location
    let text = "abcde";
    println!("'{}'", &text);
    let re = Regex::new(r"(.)(.)").unwrap();
    let result = re.replace_all(text, r"$2$1");
    println!("'{}'", &result);

    // We can use named captured and then the result might be clearer and adding another pair of ()
    // won't impact the code.
    let re = Regex::new(r"(?<first>.)(?<second>.)").unwrap();
    let result = re.replace_all(text, r"$second$first");
    println!("'{}'", &result);

    let text = "12345";
    println!("'{}'", &text);
    let re = Regex::new(r"(.)(.)").unwrap();
    let result = re.replace_all(text, |caps: &Captures| {
        let a: i32 = caps[1].parse().unwrap();
        let b: i32 = caps[2].parse().unwrap();
        format!("{} ", a + b)
    });
    println!("'{}'", &result);
}