DEV Community

BC
BC

Posted on

Day26:regex - 100DayOfRust

You can do regular expression in Rust with 3rd-party crate Regex.

In Cargo.toml:

[dependencies]
regex = "1.3.1"
Enter fullscreen mode Exit fullscreen mode

In main.rs:

use regex::{Regex, RegexBuilder, Captures};

fn main() {
    // use r"" to define a raw string
    let re_str1 = r"^(\d{4})-(\d{2})-(\d{2})$";
    let target1 = "2019-12-29";
    let re = Regex::new(re_str1).unwrap();
    // use is_match to check if there is a match
    println!("Is match: {}", re.is_match(target1));

    // iterate all captures
    let re_str2 = r"(\d{4})-(\d{2})-(\d{2})";
    let target2 = "Article created on 2019-12-28, updated on 2019-12-29";
    let re = Regex::new(re_str2).unwrap();
    for cap in re.captures_iter(target2) {
        println!("Year: {} Month: {} Day:{}", &cap[1], &cap[2], &cap[3]);
    }

    // replace
    let re_str3 = r"(\d{4})-(\d{2})-(\d{2})";
    let target3 = "Blog posted on 2019-12-29";
    // use RegexBuilder to create new regex with case-insensitive
    let re = RegexBuilder::new(re_str3)
                            .case_insensitive(true)
                            .build()
                            .unwrap();

    let replaced = re.replace(target3, |caps: &Captures| {
        format!("{}/{}/{}", &caps[2], &caps[3], &caps[1])
    });

    println!("Replaced: {}", replaced);
}
Enter fullscreen mode Exit fullscreen mode

Result:

Is match: true
Year: 2019 Month: 12 Day:28
Year: 2019 Month: 12 Day:29
Replaced: Blog posted on 12/29/2019
Enter fullscreen mode Exit fullscreen mode

Top comments (0)