How can I screen the substrings who meet the requirements in a string

for example. I have a string like this.

You have 2 parcels to Packages Station.
Please with 10-1-3125, 1-5-4453 pick
them up before 17:00.

I want to screen the strings which match the regex /[0-9]{1,2}/-/[0-9]{1}/-/[0-9]{1,2,3,4}/

how to implement it?

Have you looked into the regex crate yet?

https://docs.rs/regex

1 Like

Here’s an example

use once_cell::sync::Lazy;
use regex::Regex;

static THE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"[0-9]{1,2}-[0-9]{1}-[0-9]{1,4}").unwrap());

fn main() {
    let some_string: &str = "\
You have 2 parcels to Packages Station.
Please with 10-1-3125, 1-5-4453 pick
them up before 17:00.";

    for i in THE_REGEX.find_iter(some_string) {
        dbg!(i.as_str());
    }
}
   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 5.15s
     Running `target/debug/playground`
[src/main.rs:13] i.as_str() = "10-1-3125"
[src/main.rs:13] i.as_str() = "1-5-4453"

(in the playground)


The usage of the static Lazy<…> demonstrates a common pattern that’s useful when the same regex is needed in a function that’s called multiple times. It helps avoid the overhead of building the same regex multiple times. In this example in the main function, it is not really necessary, but I put it in to demonstrate the pattern.


The {1,4} means one up to four repititions, more details in the docs. The {1} is redundant, I should’ve probably just removed it.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.