Eric Brown
Eric Brown

Reputation: 1462

Regex Negative Lookahead not functioning as expected

I am working on an email validation that will allow email addressed to be added as long as they don't come from certain TLDs. The problem is, my Regex isn't behaving as I would expect it to. I want it to make sure that the email is valid and doesn't have some TLD, for example, I want '[email protected]' but I don't want '[email protected]' where in the second example, I am preventing a TLD of 'xyz' emails from being added. Here is my current Regex:

^[a-zA-Z0-9]+[a-zA-Z0-9._%-]*@.*\.(?!xyz)$

The problem is, where the TLD would go, it will not match anything at all. It won't match xyz, which it shouldn't, but it also wont match org, com, net, or any other TLD. I am not too advanced when it comes to Regex, but I thought that the Negative Lookahead would only block the string that comes after it, not ANYTHING that comes after it.

Any help is appreciated.

Upvotes: 0

Views: 85

Answers (1)

Daniel
Daniel

Reputation: 11162

By using negative lookahead you are telling the regex to not match xyz (?!xyz), but you're not telling it what to match.

If you want to match anything else you can just append .* after your (?!xyz):

^[a-zA-Z0-9]+[a-zA-Z0-9._%-]*@.*\.(?!xyz).*$

Upvotes: 2

Related Questions