RandomWhiteTrash
RandomWhiteTrash

Reputation: 4014

Regexp to selectively match email

I need a regexp that will matches an email that follows these rules:

It can be

[email protected]

OR

[email protected]

however it can not be any other email from mydomain.com

So far I tried using something like this:

 (\w+@[^mydomain]\w+.com)|([email protected])

however it doesnt seem to work as expected - it fails for every domain starting with m. Like [email protected] would fail and it should not. I am using PHP regexp btw.

Upvotes: 1

Views: 43

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

In your regex, [^mydomain] is a negated character class that matches 1 character that is not m, y, d, o, a, i, n. To actually restrict some generic pattern, you need to use a lookaround (here, a lookahead), i.e. (?!mydomain\.com).

Note that to match any TLD, you can use \w+ instead of hardcoding it as com.

Also, if you want to match a literal . symbol with a regex, you should either escape it (\.) or place inside a character class [.].

So, use

\w+@(?!mydomain\.com)\w+\.\w+|noreply@mydomain\.com

See regex demo

Upvotes: 1

Related Questions