0

I have a requirement such that I have some text as under

Hello 
How r u
Email: mail3456@gg.com
Another email is aaa@zz.com
And not a valid email as invalid@.com

It is a string and what I have to do is that , i need to find out whether any email address is present in the string. If so i need to extract that.

Please note that there can be multiple email addresses in the string.

Is it possible to do so using regular exprerssion.

Thanks

learner123
  • 243
  • 1
  • 4
  • 10
  • possible duplicate of [What is the best regular expression for validating email addresses?](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses) – Michael Petrotta Sep 06 '11 at 03:05
  • No, I am looking for a program that will extract a email address from a text. the regular expreesion for email address that i am using is private bool IsValidEmail(string email) { string regexPattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$"; return new Regex(regexPattern, RegexOptions.IgnoreCase).IsMatch(email); } – learner123 Sep 06 '11 at 03:09
  • If you're happy with that regex, use it (though it's not correct; see the linked question). What exactly are you asking here? – Michael Petrotta Sep 06 '11 at 03:10
  • Sir, suppose in a text there can be email address or may not. If so, then i need to extract that. – learner123 Sep 06 '11 at 03:11
  • I got that to work .. first i am spliting by spaces and then validating them using the method and placing them inside a list. – learner123 Sep 06 '11 at 03:17

3 Answers3

3

I think this article is what you need:

http://www.regular-expressions.info/email.html

It ranges from:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

To:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Paul Walls
  • 5,884
  • 2
  • 22
  • 23
1

Are there truly multiple lines of text? It appears, from this example, that each line has up to one e-mail address. I would split the text into an array of strings first, then evaluate each individual string with your regular expression of choice.

FYI, For performance reasons, you'll probably want to instantiate your regular expression before going into a loop on the array. I was recently amazed to realize the performance hit I was taking by re-instantiating a compiled regex many times. I moved into into a singleton class so that there would only over be one instance.

Community
  • 1
  • 1
sfuqua
  • 5,797
  • 1
  • 32
  • 33
0

Split you string by space characters ' ', '\n'... etc, then for each "word" containing '@' character apply: Using a regular expression to validate an email address. Even though, to me, it's exact duplicate of mentioned question.

Community
  • 1
  • 1
Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96