Best way to parse string of email addresses

后端 未结 13 2610
悲哀的现实
悲哀的现实 2021-02-14 04:10

So i am working with some email header data, and for the to:, from:, cc:, and bcc: fields the email address(es) can be expressed in a number of different ways:

F         


        
13条回答
  •  南方客
    南方客 (楼主)
    2021-02-14 04:49

    Here is the solution i came up with to accomplish this:

    String str = "Last, First , name@domain.com, First Last , \"First Last\" ";
    
    List addresses = new List();
    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);
    }
    

提交回复
热议问题