Right now I have:
(?!.*([._-])\1)(?=.*@)[\w.@-]+
which finds test@foo
I want to make it so that test
cannot start or end with a special character.
For instance, I want it to find:
tes-t@foo
test@-foo
but not:
-test@foo
test-@foo
-test-@foo
Right now I have:
(?!.*([._-])\1)(?=.*@)[\w.@-]+
which finds test@foo
I want to make it so that test
cannot start or end with a special character.
For instance, I want it to find:
tes-t@foo
test@-foo
but not:
-test@foo
test-@foo
-test-@foo
You can define a character class that doesn't include specific characters using ^
, e.g. [^a]
will match anything apart from an a
.
I would split the regex that matches the pre-@ word into three sections; one to match the leading character, one to match the middle, and one to match the last character. You'll also need to handle the special case of the pre-@ word only having a single character.
This is not an area where you should be recreating the wheel: there’s too much to get wrong.
I’m not sure what you really want to do. Addresses like president@whitehouse.gov
and a plain old postmaster
are probably both deliverable but highly unlikely to do what you want.
The only reasonable way to validate a mail address is to send mail to that address and get back a non-automatable reply showing that it is the right human at the other end. But this cannot be done in real time. Which means the best you can do is make them type it twice to try to weed out typos. That’s not much help, really. That’s why signing up for something over the web always involves a negotiated handshake.
However, if all you need is to validate an RFC 5322–compliant address, you may use this pattern.
Just understand that testing an address for compliance with the RFC should never be confused with validating that mail address — which is something else altogether.