Home > OS >  Regular expression for returning list of emails after specific set of chars (c#)
Regular expression for returning list of emails after specific set of chars (c#)

Time:10-27

I have string like this : "To: [email protected],[email protected], [email protected] ,"

I need to search for "To: ", and parse whatever after that for emails .

I know the email regx is \w ([- .]\w )*@\w ([-.]\w )*\.\w ([-.]\w )* , so when I want to add To in the regx it will be

var senderRegex = new Regex(@"(?<=To: )\w ([- .]\w )*@\w ([-.]\w )*\.\w ([-.]\w )*")

but this one will return only the first email after To . I need list of all emails any help?

CodePudding user response:

You could use

(?:To:\s |\G(?!^))(?:,\s*)?([^\s@,] @[^\s@,] )

Explanation

  • (?: Non capture group
  • To:\s Match To: and 1 whitespace chars
    • | Or
    • \G(?!^) Assert the position at the end of the previous match to get consecutive matches
  • ) Close non capture group
  • (?:,\s*)? Optionally match a comma and optional whitespace chars
  • ([^\s@,] @[^\s@,] ) Capture group 1, match non whitespace chars with a single @ char

See a enter image description here

For example

string pattern = @"(?:To:\s |\G(?!^))(?:,\s*)?([^\s@,] @[^\s@,] )";
string input = @"To: [email protected],[email protected], [email protected] ,";
RegexOptions options = RegexOptions.Multiline;

foreach (Match m in Regex.Matches(input, pattern, options))
{
    Console.WriteLine(m.Groups[1].Value);
}

CodePudding user response:

If you don't to use regular expressions, you can try the code below:

 static void Main(string[] args)
        {
            var senders = "To: [email protected], [email protected], [email protected],";
            string [] emails = senders.Split();
            emails = emails.Where(i => i != "To:").ToArray();
            foreach(var email in emails)
               Console.WriteLine("{0}", email.Replace(",",""));
            Console.ReadLine();
        }
  • Related