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 groupTo:\s
MatchTo:
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
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:
How about
[To: ]([\w.] @[\w.] )
https://regex101.com/r/d0ahg5/1
You could look into the results I pasted and iterating through all the match's 1st group.
CodePudding user response:
if you don't to use regular expression you can try below code
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();
}