Extract emails within a text string

0

I need to get the list of emails from a text string. I have tried several ways and nothing turns out. If anyone of you could help me, I would really appreciate it.

Here is my code:

string patern = @"\[A-Za-z]+@[a-z]+\.[a-z]+\";
string inputText = @"Test1 <[email protected]>, "'Carlos , Tapia'" <[email protected]>, Test2 <[email protected]>"

var matches = Regex.Matches(inputText, patern);
foreach (Match m in matches)
{
    Debug.Print(" {0}", m.Value);
}

The exit would be:

  

[email protected]

     

[email protected]

     

[email protected]

Any contribution would be great.

    
asked by ctm002 01.06.2017 в 18:45
source

2 answers

0

With the following code you can get all the emails from your chain:

const string MatchEmailPattern = @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
   + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
     + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
   + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
    Regex rx = new Regex(MatchEmailPattern,  RegexOptions.Compiled | RegexOptions.IgnoreCase);

    string text = @"Texto con los correos";
    MatchCollection matches = rx.Matches(text);
    // Número de coincidencias
    int noOfMatches = matches.Count;
    // Por cada resultado
    foreach (Match match in matches)
    {
        //Impresión de los correos
        Console.WriteLine(match.Value.ToString());
    }
    
answered by 01.06.2017 / 18:50
source
3

The main problem with your code is that you have left over the initial and final bars of the regular expression.

You should also use a regular expression that covers all cases.

You can find many examples of regular expressions on the internet to validate e-mails.

Here is an example that will work for you with a slightly more complete expression than yours:

string patern = @"\w+@\w+\.\w+";
string inputText =
    @"Test1 <[email protected]>, 'Carlos , Tapia' <[email protected]>, Test2 <[email protected]>";

var matches = Regex.Matches(inputText, patern);
foreach (Match m in matches)
{
    Debug.Print(" {0}", m.Value);
}

Still, it does not cover many cases. I left it this way for simplifying the answer.

    
answered by 01.06.2017 в 19:01