2009-03-11 14 views
1

「&」などの文字で区切られた文字列を分割したいと思いますが、一部の値に区切り文字が含まれている場合は二重引用符でエスケープします。エスケープ文字のエスケープを考慮しながらエスケープされた区切り文字を無視して、分割するためのエレガントなアプローチは何ですか?例えばカプセル化とエスケープで区切られた文字列を分割する方法

が正しく

var1=asdfasdf&var2=contain””quote&var3=”contain&delim”&var4=”contain””both&” 

には、この文字列を分割:ちなみに

var1=asdfasdf 
var2=contain"quote 
var3=contain&delim 
var4=contain"both& 

、私は正規表現...テストと

+0

特別な理由はありますか?二重引用符をエスケープ文字として使用したいですか?あなたの例では、それを使用して自分自身をエスケープするように見えるだけです。また、 'delim'と 'var4 ='の間に? – Lazarus

+0

これらの文字は実際には任意ですが、デフォルトですが、yes、ty!の間でなければなりません:) – ccook

+0

[this one]の複製(http://stackoverflow.com/questions/634777/c-extension-method-string-split-that-also-accepts-an-escape-character/)これは、これは誰かのブログでプログラミングの課題ですか? –

答えて

0

私のソリューションを、考えています:

void TestCharlesParse() 
    { 
     string s = @"var1=asdfasdf&var2=contain""""quote&var3=""contain&delim""&var4=""contain""""both&"""; 
     string[] os = CharlesParse(s); 

     for (int i = 0; i < os.Length; i++) 
      System.Windows.Forms.MessageBox.Show(os[i]); 
    } 

    string[] CharlesParse(string inputString) 
    { 
     string[] escapedQuotes = { "\"\"" }; 

     string[] sep1 = inputString.Split(escapedQuotes, StringSplitOptions.None); 

     bool quoted = false; 
     ArrayList sep2 = new ArrayList(); 
     for (int i = 0; i < sep1.Length; i++) 
     { 
      string[] sep3 = ((string)sep1[i]).Split('"'); 
      for (int j = 0; j < sep3.Length; j++) 
      { 
       if (!quoted) 
       { 
        string[] sep4 = sep3[j].Split('&'); 
        for (int k = 0; k < sep4.Length; k++) 
        { 
         if (k == 0) 
         { 
          if (sep2.Count == 0) 
          { 
           sep2.Add(sep4[k]); 
          } 
          else 
          { 
           sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + sep4[k]; 
          } 
         } 
         else 
         { 
          sep2.Add(sep4[k]); 
         } 
        } 
       } 
       else 
       { 
        sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + sep3[j]; 
       } 
       if (j < (sep3.Length-1)) 
        quoted = !quoted; 
      } 
      if (i < (sep1.Length - 1)) 
       sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + "\""; 
     } 

     string[] ret = new string[sep2.Count]; 
     for (int l = 0; l < sep2.Count; l++) 
      ret[l] = (string)sep2[l]; 

     return ret; 
    } 
関連する問題