rust using regex in if statement
You can use the regex
crate in Rust to match patterns using regular expressions in an if
statement. Here's an example:
use regex::Regex;
fn main() {
let re = Regex::new(r"^\d{4}$").unwrap();
let input = "2023";
if re.is_match(input) {
println!("Input matches the regex pattern.");
} else {
println!("Input does not match the regex pattern.");
}
}
In this example, we create a regular expression pattern that matches a string consisting of exactly four digits. We then use the is_match
method of the Regex
struct to check if the input
matches the pattern. If it does, we print a message indicating a match; otherwise, we print a message indicating no match.
Remember to add the regex
crate to your Cargo.toml
file to use it in your Rust project.