Rust, Software Development

Rust – Validate Email Address using Regular Expressions

This post shows how to validate email addresses in Rust using Regular Expressions. Although Rust does not have a standard library for regular expressions, we could use the crate regex and regular expressions on this other post.

Requirements To Validate Email

  • Rust 1.52.1
  • A Rust crate called regex

Regular Expressions To Validate Email in Rust

An email address contains two (2) parts – username and domain name. These are combined using the ‘@’ symbol, e.g., Let us create regular expressions for each for now.

For username, we can have the following regular expressions and sample codes.

When we run these codes, we get the following output.

For the domain part, we can use the following expressions with some codes for testing.

The output of these codes is as follows.

Then, we would have the following regular expressions if we combine username, @, and domain. Notice the @ symbol sits between the two regular expressions we tested before.

Test Rust Codes To Validate Email Addresses

We use some emails to validate against the regular expressions in a loop to test the combined expressions. Meaning, given the list of email addresses, we validate each using our regular expressions. Consider the following list of email addresses for testing.

As we can see, some emails use dots, +, underscores, etc. The following codes validate each email address in a loop. We use the is_match function with each email as the function’s argument.

When we run the codes, we get the following results.

When using the crate regex in Rust to validate email addresses using regular expressions, we include its dependency in the Cargo.toml file. We only need one crate for regular expressions for our Rust codes.

Finally, the complete codes look as follows.

To use the crate regex in our Rust codes, we use use regex::regex. Then, we create an instance of the Regex struct. Next, use that instance to validate an email address using a regular expression via the is_match  function.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like