What is the best regular expression to check if a string is a valid email address?
A good regular expression to validate an email address can be:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Explanation:
^[a-zA-Z0-9._%+-]+: Matches the beginning of the email and allows alphanumeric characters along with certain special characters like ._%+-.
@: Ensures the presence of the “@” symbol between the username and domain.
[a-zA-Z0-9.-]+: Matches the domain name, which can include letters, numbers, dots, and hyphens.
\.: Matches the literal dot before the domain extension.
[a-zA-Z]{2,}$: Matches the domain extension, which must be at least two characters long and consist of letters.
This regex works for most basic email formats but may not cover all edge cases defined by the official email standards.