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
  • between \w , $
    • i.e. @ end of string if ends \w

references


on using regex match e-mail addresses

this not trivial depending on specification.

related questions


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -