Regex to don't allow dots in email at wrong po

2020-03-31 08:45发布

问题:

I have to validation emails from a company. The regex should validate if it come from the company and could come from John.

My regex looks like this now:

/[a-z0-9.]*(john)[a-z0-9.]*@mycompany\.com/

The only problem, it's allows dots in wrong place. I see valid this emails:

john@mycompany.com smith.john@mycompany.com john.smith@mycompany.com

But i shouldn't see valid these:

john.@mycompany.com .john@mycompany.com

回答1:

/^([a-z0-9][a-z0-9.]*)?(john)([a-z0-9.]*[a-z0-9])?@mycompany\.com$/

This should make sure that characters before/after (john) don't start/end with a . respectively.



回答2:

Alternative solution

^(?!\.)[a-z0-9.]*(john)(?:[a-z0-9]|\.(?!@))*@mycompany\.com$



回答3:

Please try

\w+(john)?\.?\w+?@mycompany\.com

This matches

john@mycompany.com
smith.john@mycompany.com
john.smith@mycompany.com

But not

john.@mycompany.com
.john@mycompany.com

In the last case it actually grabs only the part after the dot

john@mycompany.com


回答4:

when I wrote my answer you already got many answers. :-) Ok, here is other what you can test.

^([[:alnum:]]+\.)?john(\.[[:alnum:]]+)?@mycompany\.com

I tested on regex101.com

If I understood well before and after john should be some word delimited by dot .