Regex for valid email address
A classic request!
Here is a commonly used regular expression (regex) pattern to match a valid email address:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Let's break it down:
^
matches the start of the string[a-zA-Z0-9._%+-]+
matches one or more of the following characters:- Letters (both uppercase and lowercase)
- Numbers
- Dot (.)
- Hyphen (-)
- Underscore (_)
- Percent (%)
- Plus sign (+)
@
matches the @ symbol[a-zA-Z0-9.-]+
matches one or more of the following characters:- Letters (both uppercase and lowercase)
- Numbers
- Dot (.)
- Hyphen (-)
\.
matches a period (.) character[a-zA-Z]{2,}
matches the domain extension (it must be at least 2 characters long and only contain letters)$
matches the end of the string
This regex pattern matches most common email address formats, but keep in mind that it's not foolproof and may not match all valid email addresses. Some examples of valid email addresses that this regex pattern may not match include:
- Email addresses with non-ASCII characters (e.g., accented letters or non-Latin scripts)
- Email addresses with special characters in the local part (before the @ symbol)
- Email addresses with non-standard top-level domains (TLDs)
If you need to match a more comprehensive set of email addresses, you may want to consider using a more advanced regex pattern or a dedicated email validation library.
Here's an example of how you can use this regex pattern in a programming language like JavaScript:
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = '[email protected]';
if (emailRegex.test(email)) {
console.log('Valid email address');
} else {
console.log('Invalid email address');
}
Note that this is just one example of a regex pattern for email validation, and there are many other patterns and libraries available that may be more suitable for your specific use case.