2012-12-11 118 views
2

我有這個代理地址的字符串,它們被一個空格分開,但是x400和x500將空格處理到它們的地址中。什麼是分割它的最佳方法。將它拆分成一個數組

例如

smtp:[email protected] smtp:[email protected] smtp:[email protected] X400:C=us;A= ;P=mygot;O=Exchange;S=John;G=Gleen; SMTP:[email protected] 

預期結果:

smtp:[email protected] 
smtp:[email protected] 
smtp:[email protected] 
X400:C=us;A= ;P=mygot;O=Exchange;S=John;G=Gleen; 
SMTP:[email protected] 

感謝,

EDIT,

 string mylist = "smtp:[email protected] smtp:[email protected] smtp:[email protected] X400:C=us;A= ;P=mygot;O=Exchange;S=John;G=Gleen; SMTP:[email protected] X500:/o=Example/ou=USA/cn=Recipients of /cn=juser smtp:myaddress"; 

     string[] results = Regex.Split(mylist, @" +(?=\w+:)"); 
     foreach (string part in results) 
     { 
      Console.WriteLine(part); 
     } 

結果

smtp:[email protected] 
smtp:[email protected] 
smtp:[email protected] 
X400:C=us;A= ;P=mygot;O=Exchange;S=John;G=Gleen; 
SMTP:[email protected] 
X500:/o=Example/ou=USA/cn=Recipients of /cn=juser 
smtp:myaddress 
+1

好吧,你可以在SMTP上分割,然後再添加它,或者是時候享受正則表達式了。 –

+0

獲取smtp和x400,x400和下一個smtp之間的子字符串。 然後拆分單個字符串(實際上只有一個字符串..第一個子字符串)。 –

+0

OP - 你有控制輸入嗎? –

回答

5

下面是協議前,應符合空格的正則表達式。嘗試將它變成Regex.Split像這樣:

string[] results = Regex.Split(input, @" +(?=\w+:)"); 
+0

我選擇這個是因爲它簡潔,謝謝 – m0dest0

-1

我認爲以下行應該做的工作

var addrlist = variable.Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries); 
+0

我不認爲這將工作,因爲A =後有一個空格。 –

+0

請在回答之前閱讀問題。 –

1
int index = smtp.indexOf("X400") ; 
string[] smtps = smtpString.SubString(0,index).Split(" ") ; 
int secondIndex = smtpString.indexOf("SMTP"); 
string xfour = smtpString.substring(index,secondIndex); 
string lastString = smtpString.indexOf(secondIndex) ; 

應該工作,如果字符串格式是這樣..如果我沒有搞砸的指標。雖然你可能要檢查指數不爲-1

1

試試這個:

public static string[] SplitProxy(string text) 
     { 
      var list = new List<string>(); 
      var tokens = text.Split(new char[] { ' ' }); 
      var currentToken = new StringBuilder(); 

      foreach (var token in tokens) 
      { 
       if (token.ToLower().Substring(0, 4) == "smtp") 
       { 
        if (currentToken.Length > 0) 
        { 
         list.Add(currentToken.ToString()); 
         currentToken.Clear(); 
        } 

        list.Add(token); 
       } 
       else 
       { 
        currentToken.Append(token); 
       } 
      } 

      if (currentToken.Length > 0) 
         list.Add(currentToken.ToString()); 

      return list.ToArray(); 
     } 

它分裂空格爲標記的字符串,然後通過逐一去。如果令牌以smtp開頭,它將被添加到結果數組中。如果不是,那麼該令牌會與下列令牌一起被創建爲創建一個條目,而不是添加到結果數組中。應該處理任何有空格但不以smtp開頭的東西。