Match the email address if it contains a period

I want to match any email address that contains at least one . (period) before the @ sign. Letters have already been verified, so regular expression just needs to be searched . .

I 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\.' therefore it will not cover all cases.

Any ideas on how to do this?

thanks

EDIT: I'm not trying to check emails, I already have verified emails, I just need to select emails containing . before @ sign

Examples to pass:

 first.last@example.com first.middle.last@example.com 

Examples that should pass but will not pass using the current current regular expression

 first.last(comment)@example.com 
+5
source share
5 answers

You can do it without regex

 Func<string, bool> dotBeforeAt = delegate(string email) { var dotIndex = email.IndexOf("."); return dotIndex > -1 && (dotIndex < email.IndexOf("@")); }; ... emails.Where(dotBeforeAt).ToList(); 

Try

+7
source

I just need to select the ones that contain the dot before the @ sign

Then it makes no sense to create a regular expression that matches valid email addresses. All you need is a regular expression that sees that there is a dot in front of the @ sign:

 (?<=[.][^@]*)@ 

(?<=[.][^@]*) is a positive lookbehind construct. This ensures that the @ sign following it will only match when it is preceded by a dot [.] Followed by zero or more non- @ characters.

+3
source

You can use lookahead .. for this purpose ..

 (?=\.) .+@ 

Explanation:

  • Look at the dot followed by any characters followed by @

Edit: To match an email with the above criteria, you can use

 .+(?=\ ..+@ ).+ 

See DEMO

+2
source

LinQ can be used both to exclude regular expressions 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(); 
+2
source

James's answer is likely to give you better performance. However, the IndexOf approach does not process the quoted string (ie " abc@.xtest.yz "@example.com , which is a valid address according to RCF 5322 ). To support this case, and if performance is not an issue, you can also use the following, which is a bit more readable and detailed as to what the LINQ query is:

 emails.Select(m => new MailAddress(m)).Where(m => m.User.Contains('.')).ToList(); 

The overhead of creating MailAddress objects MailAddress pretty obvious, but it's really clear that you want these addresses to have a dot in the local part of the address.

+2
source

All Articles