Regular expressions (regex) are used to match patterns in strings, making them ideal for email validation. To validate an email using regex, we would create a pattern that matches the general structure of an email address.
The basic structure of an email is: local-part@domain.com. The local part can contain alphanumeric characters and special symbols like dot, hyphen or underscore. The domain part contains two sections separated by a dot – the domain name and the top-level domain.
A simple regex pattern for this could be: ^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$
This pattern checks if the string starts (^) with one or more (+) alphanumeric characters (a-z, A-Z, 0-9), dots (.), underscores (_), percent signs (%) or hyphens (-). This is followed by an @ symbol, then another set of one or more alphanumeric characters, dots or hyphens. Finally, it checks for a dot (\.) followed by two to six alphabetic characters {2,6}, which represent the top-level domain, before the end of the string ($).