Reputation: 2351
I want to match any email address, that contains at least one .
(dot) before the @
sign. The emails have already been validated, so the regex just needs to search for the .
.
I have tried
Regex emailMatcher = new Regex(@"^[a-zA-Z\.']{1,}\.[a-zA-Z\.']{1,}@example\.com$");
But I know that emails can contain more characters than just a-zA-Z\.'
so this won't cover all cases.
Any ideas on how to do it?
Thanks
EDIT:
I'm not trying to validate emails, I already have the emails validated, I just need to select emails, that contain .
before @
sign
Examples that would pass:
[email protected]
[email protected]
Examples that should pass, but wouldn't pass using my current regex
first.last(comment)@example.com
Upvotes: 5
Views: 3290
Reputation: 10859
James' answer will probably give you the best performance. However, the IndexOf
approach will not handle a quoted-string (ie. "[email protected]"@example.com
, which is a valid address according to RCF 5322). To support that case, and if performance is not an issue, you could also use the following, which is a little bit more readable and verbose on what the intention of the LINQ query is:
emails.Select(m => new MailAddress(m)).Where(m => m.User.Contains('.')).ToList();
The overhead of building the MailAddress
objects is pretty obvious, but this makes it really clear that you want those addresses that have a dot in the local part of the address.
Upvotes: 2
Reputation: 43254
LinQ could be used to both avoid a regex and to avoid calling IndexOf()
twice on ".":
var dottyEmails = (from email in emails
let dotIndex = email.IndexOf(".")
let atIndex = email.IndexOf("@")
where dotIndex >= 0 && dotIndex < atIndex
select email).ToList();
Upvotes: 2
Reputation: 82096
You could do this without a regex
Func<string, bool> dotBeforeAt = delegate(string email)
{
var dotIndex = email.IndexOf(".");
return dotIndex > -1 && (dotIndex < email.IndexOf("@"));
};
...
emails.Where(dotBeforeAt).ToList();
Upvotes: 7
Reputation: 13640
You can use lookahead.. for this purpose..
(?=\.).+@
Explanation:
@
Edit: To match the email with the above criteria.. you can use
.+(?=\..+@).+
See DEMO
Upvotes: 2
Reputation: 726589
I just need to select ones, that contain dot before @ sign
Then there is no point to build a regex that matches valid e-mail addresses. All you need is a regex that sees that there is a dot in front of the @
sign:
(?<=[.][^@]*)@
(?<=[.][^@]*)
is a positive lookbehind construct. It ensures that the @
sign following it is matched only when there is a dot [.]
followed by zero or more non-@
characters in front of it.
Upvotes: 3