So, there is a task to match emails in an input agains some certain conditions. Most of them are fulfilled. All of them, actually, except one.
So, user emails have to be up to 30 characters long, but they cannot be shorter than 6 only for gmail users (the part before the @). Other types of email can have even shorter emails.
Please help me find a correct regexp!
My current one is:
^((?!.*?\.\.)[a-zA-Z0-9\.]{1,30})\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$
Using a case insensitive match, you could write the pattern as:
^(?!.*?\.\.)(?:[a-zA-Z0-9.]{1,30}@(?!gmail\.com$)(?:[a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,4}|[a-zA-Z0-9.]{6,30}@gmail\.com)$
The pattern matches:
^ Start of string(?!.*?\.\.) Assert not .. to the right(?: Non capture group for the 2 alternatives
[a-z0-9.]{1,30} Match 1-30 chars specified in the character class@(?!gmail\.com$) Match @ and assert not followed by gmail.com(?:[a-z0-9-]+\.)+[a-z0-9]{2,4} Match 1+ repetitions of the character class and . and match 2-4 chars of the second character class| Or[a-zA-Z0-9.]{6,30}@gmail\.com) Close non capture group$ End of stringconst regex = /^(?!.*?\.\.)(?:[a-zA-Z0-9.]{1,30}@(?!gmail\.com$)(?:[a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,4}|[a-zA-Z0-9.]{6,30}@gmail\.com)$/i;
[
"testing@test.com",
"t@gmail.com",
"t@test.com",
"testing@gmail.com"
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));
A bit shorter way to write it could be asserting not 1-5 characters before gmail.com:
^(?!.*?\.\.)(?![a-z0-9.]{1,5}@(?=gmail\.com$))[a-z0-9.]+@(?:[a-z0-9-]+\.)+[a-zA-Z0-9]{2,4}$