rust check valid email address using regex
To check if an email address is valid using a regular expression in Rust, you can use the regex
crate. Here's an example of how you can accomplish this:
use regex::Regex;
fn is_valid_email(email: &str) -> bool {
let email_regex = Regex::new(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$").unwrap();
email_regex.is_match(email)
}
fn main() {
let email = "[email protected]";
if is_valid_email(email) {
println!("Valid email address");
} else {
println!("Invalid email address");
}
}
In this example, we define a function is_valid_email
that takes an email address as a parameter and returns a boolean indicating whether the email address is valid or not. The regular expression used to validate the email address is ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
.
The is_match
method of the Regex
struct is used to check if the email address matches the regular expression. If it does, we consider it a valid email address.
In the main
function, we call is_valid_email
with an example email address and print the corresponding message based on the result. Keep in mind that this is a basic example, and you can modify the regular expression to suit your specific requirements for validating email addresses.