Regular expression which matches a pattern, or is an empty string

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

Explanation

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

  • regular-expressions.info/Anchors and Alternation

  • On b

    b in most flavor is a "word boundary" anchor. It is a zero-width match, ie 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):
  • ie between a word character and a non-word character
  • Between ^ and w
  • ie at the beginning of the string if it starts with w
  • Between w and $
  • ie at the end of the string if it ends with w
  • References

  • regular-expressions.info/Word Boundaries

  • On using regex to match e-mail addresses

    This is not trivial depending on specification.

    Related questions

  • What is the best regular expression for validating email addresses?
  • Regexp recognition of email address hard?
  • How far should one take e-mail address validation?

  • An alternative would be to place your regexp in non-capturing parentheses. Then make that expression optional using the ? qualifier, which will look for 0 (ie empty string) or 1 instances of the non-captured group.

    For example:

    /(?: some regexp )?/
    

    In your case the regular expression would look something like this:

    /^(?:[w.-]+@([w-]+.)+[a-zA-Z]+)?$/
    

    No | "or" operator necessary!

    Here is the Mozilla documentation for JavaScript Regular Expression syntax.


    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.

    链接地址: http://www.djcxy.com/p/92752.html

    上一篇: 为什么人们使用regexp进行电子邮件和其他复杂的验证?

    下一篇: 正则表达式匹配模式,或者是空字符串