Regex API and code

Regular Expressions and manipulations

A regular expression is a sequence of characters that defined a search pattern for matching text. It can be a single character or a complex pattern.

You need to have a piece of text.

#![allow(unused)]

fn main() {
let text: &str = "Name:Bobby, Age:26, Time: 1530";

}

Now you need a regular expression.

#![allow(unused)]

fn main() {
let re = Regex::new(r"\d+").unwrap();

}

Regex::new() returns a result type Result<Regex, regex::Error> If the pattern is malformed it will return an error. Err(regex::Error). unwrap() panics and crashes the program and hence it should be used in the compile time only.

#![allow(unused)]
fn main() {
use regex::Regex;

fn extract_numbers(text: &str) -> Result<Vec<String>, regex::Error> {

let re = Regex::new(r"\d+")?;
let numbers: Vec<String> = re.find_iter(text).map(|m|m.as_str().to_string()).collect();
Ok(numbers);

}

}

Handle the results unless the patten is trivially correct.

Compiling a regex is expensive so store it in a lazy static object.


use once_cell::sync::Lazy;

static RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(\d{4})-(\d{2})-(\d{3})").expect("Invalid regex")});


fn main() {

let text:&str = "Today is 2023-12-12";
if let Some(caps) = RE.captures(text) {
        println!("Year: {}, Month: {}, Day: {}", &caps[1], &caps[2], &caps[3]);
    }

}