Regex empty string or email

RegexEmailString

Regex Problem Overview


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 email only? I want to have this on Regex only.

Regex Solutions


Solution 1 - Regex

This regex pattern will match an empty string:

^$

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

(^$|^.*@.*\..*$)

Solution 2 - Regex

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

Solution 3 - Regex

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

Solution 4 - Regex

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

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

Solution 5 - Regex

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

"^$|^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"

Solution 6 - Regex

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 }

Solution 7 - Regex

Don't match an email with a regex. It's extremely ugly and long and complicated and your regex parser probably can't handle it anyway. Try to find a library routine for matching them. If you only want to solve the practical problem of matching an email address (that is, if you want wrong code that happens to (usually) work), use the regular-expressions.info link someone else submitted.

As for the empty string, ^$ is mentioned by multiple people and will work fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrob waminalView Question on Stackoverflow
Solution 1 - RegexDave ChildView Answer on Stackoverflow
Solution 2 - RegexStofkeView Answer on Stackoverflow
Solution 3 - RegexChemistView Answer on Stackoverflow
Solution 4 - RegexThomasReggiView Answer on Stackoverflow
Solution 5 - RegexLijish BhavanView Answer on Stackoverflow
Solution 6 - RegexSalma GomaaView Answer on Stackoverflow
Solution 7 - RegexKevinView Answer on Stackoverflow