javascript - Regular expression which matches a pattern, or is an empty string -
i have following regular expression matches email address format:
^[\w\.\-]+@([\w\-]+\.)+[a-za-z]+$
this used validation form using javascript. however, optional field. therefore how can change regex match email address format, or empty string?
from limited regex knowledge, think \b
matches empty string, , |
means "or", tried following, didn't work:
^[\w\.\-]+@([\w\-]+\.)+[a-za-z]+$|\b
to match pattern
or empty string, use
^$|pattern
explanation
^
,$
beginning , end of string anchors respectively.|
used denote alternates, e.g.this|that
.
references
on \b
\b
in flavor "word boundary" anchor. zero-width match, i.e. empty string, matches strings @ very specific places, namely @ boundaries of word.
that is, \b
located:
- between consecutive
\w
,\w
(either order):- i.e. between word character , non-word character
- between
^
,\w
- i.e. @ beginning of string if starts
\w
- i.e. @ beginning of string if starts
- between
\w
,$
- i.e. @ end of string if ends
\w
- i.e. @ end of string if ends
references
on using regex match e-mail addresses
this not trivial depending on specification.
Comments
Post a Comment