Code

These are regular expressions to validate email addresses. They are not intended to be used with any modifiers including case insensitive switch. For a really small performance improvement, you can combine the regular expressions into one and use non-capturing group (?:regex).

\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z

^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*



Example in PHP

function isValidEmail($email)
{
    return preg_match('/\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z/', $email)
        && preg_match('/^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/', $email);
}


Example in JavaScript

function isValidEmail(email)
{
    return /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test(email)
        && /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test(email);
}
JavaScript does not support \A and \z, so ^ and $ must be used instead.


Example in Java

public static boolean isValidEmail(String email) {
    return email.matches("\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z")
        && email.matches("^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
}
In Java strings a backslash is written as double backslashes.


Example in C#

using System.Text.RegularExpressions;

public static bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
        && Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
}


Example in Objective-C

- (BOOL)isValidEmail:(NSString *)email
{
    NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
    NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
    NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
}
In Objective-C strings a backslash is written as double backslashes. With iOS 4 and later it is possible to use NSRegularExpression instead of NSPredicate to match regular expressions.


Example in Python

import re

def is_valid_email(email):
    regex1 = r"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\Z"
    regex2 = r"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*"
    return (re.match(regex1, email) is not None
        and re.match(regex2, email) is not None)
Python does not support \z, so \Z must be used instead.


No comments:

Post a Comment