Regex empty string or email

前端 未结 7 1157
情深已故
情深已故 2020-11-29 20:46

I found a lot of Regex email validation in SO but I did not find any that will accept an empty string. Is this possible through Regex only? Accepting either empty string or

相关标签:
7条回答
  • 2020-11-29 21:05

    matching empty string or email

    (^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)
    

    matching empty string or email but also matching any amount of whitespace

    (^\s*$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)
    

    see more about the email matching regex itself:

    http://www.regular-expressions.info/email.html

    0 讨论(0)
  • 2020-11-29 21:05

    this will solve, it will accept empty string or exact an email id

    "^$|^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
    
    0 讨论(0)
  • 2020-11-29 21:20

    If you are using it within rails - activerecord validation you can set allow_blank: true

    As:

    validates :email, allow_blank: true, format: { with: EMAIL_REGEX }
    
    0 讨论(0)
  • 2020-11-29 21:27

    This regex pattern will match an empty string:

    ^$
    

    And this will match (crudely) an email or an empty string:

    (^$|^.*@.*\..*$)
    
    0 讨论(0)
  • 2020-11-29 21:28

    The answers above work ($ for empty), but I just tried this and it also works to just leave empty like so:

    /\A(INTENSE_EMAIL_REGEX|)\z/i
    

    Same thing in reverse order

    /\A(|INTENSE_EMAIL_REGEX)\z/i
    
    0 讨论(0)
  • 2020-11-29 21:29

    I prefer /^\s+$|^$/gi to match empty and empty spaces.

    console.log("  ".match(/^\s+$|^$/gi));
    console.log("".match(/^\s+$|^$/gi));

    0 讨论(0)
提交回复
热议问题