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
Thus the empty string "" always matches A* for any A . Here are some examples. These regular expressions are matched by the following strings: as_then_b matches any string of zero or more a 's, followed by any single character, followed by a b.
The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string.
A regular expression is a pattern of text that consists of ordinary characters, for example, letters a through z, and special characters. Matches pattern anywhere in the name. Marks the next character as either a special character, a literal, a back reference, or an octal escape.
∅, the empty set, is a regular expression. ∅ represent the language with no elements {}.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With