[英]How to split recipient name and email address using regular expressions in C#?
I have a string array which contains email recipients' names and emails. 我有一个字符串数组,其中包含电子邮件收件人的姓名和电子邮件。 To send the relevant emails I need to split the values using regular expression.
要发送相关电子邮件,我需要使用正则表达式拆分值。 I'm new to this regex area:
我是这个正则表达式领域的新手:
Here is the string array 这是字符串数组
[
"Jason D Silva <ejd@yopmail.com>",
"Aruna Nishantha <arunan@yopmail.com>",
"Dan Carter <dancarter@yopmail.com>"
]
I want to split values into Name and Email. 我想将值分为“名称”和“电子邮件”。 Once the split is done correctly i'm going to insert that to a list as follows:
正确完成拆分后,我将其插入列表,如下所示:
List<KeyValuePair<string, string>> recipientList = new List<KeyValuePair<string, string>>();
foreach (var item in recipients)
{
// Regex pattern
if (true)
{
//add to recipientList
}
}
Any help for regex pattern pls? 对正则表达式模式有帮助吗?
You could use following regular expression: 您可以使用以下正则表达式:
^(?<Name>.*)\s\<(?<Email>.*)\>$
With this you can retrieve the name and the e-mail address with: 使用此工具,您可以使用以下方法检索名称和电子邮件地址:
var match = Regex.Match("Jason D Silva <ejd@yopmail.com>", @"^(?<Name>.*)\s\<(?<Email>.*)\>$");
var email = match.Groups["Email"].Value;
var name = match.Groups["Name"].Value;
A proper implementation with String.Substring
method String.Substring
方法的正确实现
int start, end;
String[] a = {"Jason D Silva <ejd@yopmail.com>","Aruna Nishantha <arunan@yopmail.com>","Dan Carter <dancarter@yopmail.com>" };
foreach (String item in a)
{
Console.WriteLine(item);
end = item.IndexOf('<');
Console.WriteLine(" \t Name : " + item.Substring(0, end));
start = item.IndexOf('<');
end = item.IndexOf('>');
Console.WriteLine(" \t email : " + item.Substring(start + 1, end - (start + 1)));
}
Output : 输出:
"Jason D Silva <ejd@yopmail.com>"
Name : Jason D Silva
email : ejd@yopmail.com
"Aruna Nishantha <arunan@yopmail.com>"
Name : Aruna Nishantha
email : arunan@yopmail.com
"Dan Carter <dancarter@yopmail.com>"
Name : Dan Carter
email : dancarter@yopmail.com
You don´t need regex for this, you may just use String.Split
instead: 您不需要正则表达式,可以只使用
String.Split
:
string[] myArray = // ...
foreach(string kv in myArray)
{
string[] values = kv.Split(" <");
// to eliminate the terminating ("noisy" > at the end
values[1] = values[1].Substring(0, values[1].IndexOf('>');
}
This of course assumes that you strings will always look the same. 当然,这假定您的字符串将始终看起来相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.