Regular Expression Question for Emails

  • Thread starter Thread starter Arin
  • Start date Start date
A

Arin

We've got a email regular expression validator that currently looks
like the following:

\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

This is mostly fine, but doesn't allow email addresses with single
quotes or underscores in the first part of the email address (before
the @).

I need to change it to allow ' and _ in the first part. I've found
this regular expression on the 15 Seconds website that allows
underscores, but still doesn't allow for single quotes.

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

How do I modify the above regular expression to also allow single
quotes? I'm no regular expression expert at all, in fact I haven't
been able to get my head around why the 2nd expression does allow
underscores when the first doesn't.

Here's a bogus email address you can use to test the above
expressions.

patty_o'(e-mail address removed)

thanks for any help you can provide.

-Arin
 
Hermit Dave said:
have a look at http://www.regexlib.com/
you should find just about any sort you are looking for.


I tried that site too, but I can't find anything there that allows
single quotes or apostrophes in it. Most allow the underscore.
Anybody know regular expressions well enough to change this regex to
also allow single quotes in front of the @ sign?

^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$
 
Just include the ' character in the character class:

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

If you want to get a better understanding of regular expressions in general
(which I strongly recommend, since it's a very powerful tool), I'd suggest
reading J. Friedl's "Mastering Regular Expressions", and getting a free
regex building tool like Expresso (www.ultrapico.com)

Niki
 
Back
Top