How to use regex in Rust

Use the regex crate with Regex::new() to compile patterns and replace_all() to transform strings in Rust.

Use the regex crate to compile patterns into Regex objects, then call methods like replace_all or is_match to process strings.

use regex::Regex;

let re = Regex::new(r"(?m)^ >").unwrap();
let fixed = re.replace_all(" > Hello", ">");
println!("{}", fixed);

For static patterns, use lazy_static! to compile once at runtime:

use lazy_static::lazy_static;
use regex::Regex;

lazy_static! {
    static ref EXTRA_SPACE: Regex = Regex::new(r"(?m)^ >").unwrap();
}

let fixed = EXTRA_SPACE.replace_all(" > Hello", ">");

To match filenames or paths, compile patterns into a vector and iterate:

use regex::Regex;

let patterns = vec![
    (Regex::new(r"ch(\d\d)-\d\d-.*\.md").unwrap(), "chapter$1.md"),
];

let filename = "ch01-01-installation.md";
for (re, replacement) in &patterns {
    if re.is_match(filename) {
        let target = re.replace_all(filename, replacement);
        println!("{}", target);
    }
}