Regex to reject specific email
I am trying to write a regex to match emails such that it rejects two email addresses test@testdomain.com
and tes2@testdomain.com
and match all other email addresses from a specific domain. So far, I have made the following pattern:
^(?!test@testdomain.com|tes2@testdomain.com)|(A-Z0-9)[A-Z0-9._%+-]+@testdomain.com$
So far, it is able to reject the main email addresses I want to block, but it accepts all other strings through this. As an alternative, I wrote the following regex:
^(?!test|tes2)[A-Z0-9._%+-]+@testdomain.com$
However, this rejects all patterns that start with either test or tes2 exclusively.
What is a better regular expression to get this scenario achieved?
"Fixing" your regex, you need to make sure you also test for @
inside the lookahead patterns to match test
and tes2
as full user names:
^(?!test@|tes2@)[A-Za-z0-9._%+-]+@testdomain.com$
^ ^
Remember to escape a dot, too. See the regex demo.
However, you might want to be less restrictive on the user name part, and just use S+
instead of your character class:
^(?!test@|tes2@)S+@testdomain.com$
^^^
See another regex demo. The S+
pattern matches any 1 or more chars other than whitespace characters.
上一篇: var($ email,FILTER
下一篇: 正则表达式拒绝特定的电子邮件