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
To match pattern
or an empty string, use
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.\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:
\w
and \W
(either order):
^
and \w
\w
\w
and $
\w
This is not trivial depending on specification.