How to use regex to match an email address in C#
Regular expressions, commonly known as regex, are utilized to match specific patterns within strings. These patterns can encompass alphanumeric characters as well as special characters.
The table below contains some regex rules needed to make a pattern to validate an email address:
Regex rules for email address validation
Pattern | Explanation |
| The regex pattern |
| The regex pattern |
| |
|
|
| When a plus sign ( |
Regular expression
Let's now build the regular expression to match an email address using the above rules:
^[a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
Here's a breakdown of how the regular expression works:
^asserts the start of the string.[a-zA-Z0-9.!#$%&'*+-/=?^_{|}~]+`matches one or more characters from the set of alphabets (lowercase and uppercase), digits, and special characters that are allowed in the local part of an email address.@matches the "@" symbol.[a-zA-Z0-9-]+matches one or more characters from the set of alphabets (lowercase and uppercase), digits, and hyphens that are allowed in the domain name part of an email address.(?:\.[a-zA-Z0-9-]+)*is a non-capturing group that matches zero or more occurrences of a dot followed by one or more characters from the set of alphabets (lowercase and uppercase), digits, and hyphens. This allows for multiple domain levels, such as "example.com" or "subdomain.example.com".$asserts the end of the string.
Overall, this regular expression can be used to validate that a given string represents a valid email address.
Let's now look at a coding example to match an email address.
Coding example
using System;using System.Text.RegularExpressions;public class Program{public static void Main(){string[] email_addrs = { "test@example.com", "user@example@com", "invalid_email" };foreach (string i in email_addrs){bool is_Valid_Email = ValidateEmail(i);if (is_Valid_Email){Console.WriteLine($"{i} is a valid email address.");}else{Console.WriteLine($"{i} is an invalid email address.");}}}public static bool ValidateEmail(string Email_Address){string reg_pattern = @"^[a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$";Regex regex = new Regex(reg_pattern);return regex.IsMatch(Email_Address);}}
Explanation
Lines 6–23: In the function
Main, we define an array of email addresses (email_addrs) that need to be validated. The program then iterates over each email address in the array and calls theValidateEmailfunction to check if it is valid.Lines 25–32: The
ValidateEmailfunction takes an email address as input and returns a boolean value indicating whether the email address is valid or not. It utilizes a regular expression pattern to perform the validation. The function creates aRegexobject with the pattern and uses theIsMatchmethod to check if the email address matches the pattern.
The program outputs a message indicating whether each email address is valid or invalid based on the validation result.
Free Resources