-1

I am having a hard time forming a regex expression to check if a string of random words contains an email address. For example:

string str = "Hello, thank you for viewing my ad. Please contact me on the phone number below, or at abcd@gmail.com"  

=Match

string str - "Hello, thank you for viewing my ad. Please contact me on the phone number below" 

=No match

How can I check whether a string contains an email address using regex? Any help would be highly appreciated.

abruzzi26
  • 159
  • 1
  • 10

1 Answers1

0

There are a lot of RegEx variations for retrieving an email address which are different by strictness. Just follow the link and choose appropriate one according to your needs. http://www.regular-expressions.info/email.html

For most of the needs the next pattern can be used

Regex pattern = new Regex(@"
                            \b                   #begin of word
                            (?<email>            #name for captured value
                                [A-Z0-9._%+-]+   #capture one or more symboles mentioned in brackets
                                @                #@ is required symbol in email per specification
                                [A-Z0-9.-]+      #capture one or more symboles mentioned in brackets
                                \.               #required dot
                                [A-Z]{2,}        #should be more then 2 symboles A-Z at the end of email
                            )
                            \b                   #end of word
                                    ", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);

            var match = pattern.Match(input);
            if (match.Success)
            {
                var result = match.Groups["email"];
            }

Keep in mind that this pattern is not 100% reliable. It works perfect with strings like

string input = "This can be recognized as email heymail@gmail.company.com";

But in string

string input = "This can't be recognized as email hey@mail@gmail.com";

It captures "mail@gmail.com" in spite of the fact that this email is incorrect per specification.

managerger
  • 728
  • 1
  • 10
  • 31
  • Link only answers are not an answer. Include some relevant text from the link in your answer so that it will still be useful if the link breaks. – Tezra Jul 27 '17 at 17:38