我正在处理一些电子邮件头数据,对于收件人(to:)、发件人(from:)、抄送人(cc:)和密送人(bcc:)字段,电子邮件地址可以采用多种不同的方式表示:
First Last <name@domain.com>
Last, First <name@domain.com>
name@domain.com
这些变体可以以任何顺序出现在同一条消息中,全部出现在一个逗号分隔的字符串中:
First, Last <name@domain.com>, name@domain.com, First Last <name@domain.com>
我一直在尝试想出一种方法,将此字符串解析为每个人的单独名字、姓氏和电子邮件(如果仅提供电子邮件地址,则省略名称)。
有人能建议最好的方法吗?
我已经尝试了逗号分隔,这个方法本来可以工作,但在第二个示例中,姓氏被放在了首位。我想这种方法可能可行,如果我在拆分后检查每个元素并查看它是否包含“@”或 “<”/“>”,如果不包含,则可以假定下一个元素是名字。这是一种好的方法吗?还有其他格式的地址我忽略了吗?
更新:也许我应该稍微澄清一下,基本上我要做的就是将包含多个地址的字符串拆分成包含以任何格式发送的地址的单个字符串。我有自己的方法来验证和从地址中提取信息,只是对我来说难以找到最好的方法来分隔每个地址。
以下是我想出来的解决方案:
String str = "Last, First <name@domain.com>, name@domain.com, First Last <name@domain.com>, \"First Last\" <name@domain.com>";
List<string> addresses = new List<string>();
int atIdx = 0;
int commaIdx = 0;
int lastComma = 0;
for (int c = 0; c < str.Length; c++)
{
if (str[c] == '@')
atIdx = c;
if (str[c] == ',')
commaIdx = c;
if (commaIdx > atIdx && atIdx > 0)
{
string temp = str.Substring(lastComma, commaIdx - lastComma);
addresses.Add(temp);
lastComma = commaIdx;
atIdx = commaIdx;
}
if (c == str.Length -1)
{
string temp = str.Substring(lastComma, str.Legth - lastComma);
addresses.Add(temp);
}
}
if (commaIdx < 2)
{
// if we get here we can assume either there was no comma, or there was only one comma as part of the last, first combo
addresses.Add(str);
}
上述代码生成了各个地址,我可以在后续操作中进一步处理这些地址。