views:

118

answers:

3

I have the following Regular Expression which matches an email address format:

^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$

This is used for validation with a form using javascript. However, this is an optional field. Therefore how can I change this regex to match an email address format, or an empty string?

From my limited regex knowledge, I think \b matches an empty string, and | means "Or", so I tried to do the following, but it didn't work:

^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$|\b

Cheers,

Curt

A: 

\b matches a word boundary. I think you can use ^$ for empty string.

pritaeas
+4  A: 

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

polygenelubricants
+1  A: 

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use

^$|^[^@\s]+@[^@\s]+$` 

meaning

^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
@         
[^@\s]+
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

Zano
If an address isn't entered into the field, a NULL value is entered into the database, therefore this can be dealt with when it comes to sending out newsletters etc. I appreciate this won't stop fake addresses, and I don't think thats possible at all with Regex, but it'll at least minimise human-error
Curt