Useful regular expressions

Everybody seems to have his own version of regular expressions for checking the validity of emails and URLs. I’ve combined serveral versions I found on the net to create my own.

Here’s the regular expression for checking the validity of email addresses:

^[a-zA-Z][w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$

And here’s the regular expression for checking the validity of URLs:

^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/?.*)$

These regular expressions should work anywhere Perl-style regular expressions are supported (at least Perl, Python and Ruby), but I code in Python so here’s the code for the lazy ones among you:

def is_valid_email(email):
"""Returns True if ‘email’ is a valid email address"""
validEmail = """
^[a-zA-Z][w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$"
""

if re.match(validEmail, email):
return True
else:
return False

def is_valid_url(url):
"""Returns True if ‘url’ is a valid HTTP URL address"""
validUrl = """
^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/?.*)$"
""

if re.match(validUrl, url):
return True
else:
return False

Comments are closed.