2012-12-17 88 views
3
之間

我期待通過逗號分割這樣的字符串:用逗號分割,如果是逗號不是位於兩個雙引號

field1:"value1", field2:"value2", field3:"value3,value4" 

string[]那會是什麼樣子:

0  field1:"value1" 
1  field2:"value2" 
2  field3:"value3,value4" 

我試圖用Regex.Split這樣做,但似乎無法解決正則表達式問題。

+4

難道你不能只分裂'',在這種情況下?' – webnoob

+0

@webnoob這也將刪除尾隨'''太,只是爲了銘記。 – LukeHennerley

+0

@LukeHennerley - 如果你知道它會被忽略,那麼在需要的時候把它放回去並不多。 – webnoob

回答

7

這將是比Split容易得多Matches要做到這一點,例如

string[] asYouWanted = Regex.Matches(input, @"[A-Za-z0-9]+:"".*?""") 
    .Cast<Match>() 
    .Select(m => m.Value) 
    .ToArray(); 

但如果有你的價值觀的任何機會(或領域!)含有轉義引號(或任何同樣棘手),那麼使用適當的CSV解析器可能會更好。


如果在你的價值觀做逃脫報價,我認爲下面的正則表達式工作 - 給它一個測試:

@"field3:""value3\\"",value4""", @"[A-Za-z0-9]+:"".*?(?<=(?<!\\)(\\\\)*)""" 

增加的(?<=(?<!\\)(\\\\)*)應該確保它停止匹配的"之前只有偶數的斜槓,因爲奇數的斜槓意味着它被轉義。

1

未經測試,但是這應該是好的:

string[] parts = string.Split(new string[] { ",\"" }, StringSplitOptions.None); 

記得添加「回結束時,如果你需要它

0

試試這個

// (\w.+?):"(\w.+?)"   
//   
// Match the regular expression below and capture its match into backreference number 1 «(\w.+?)»   
// Match a single character that is a 「word character」 (letters, digits, and underscores) «\w»   
// Match any single character that is not a line break character «.+?»   
//  Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»   
// Match the characters 「:"」 literally «:"»   
// Match the regular expression below and capture its match into backreference number 2 «(\w.+?)»   
// Match a single character that is a 「word character」 (letters, digits, and underscores) «\w»   
// Match any single character that is not a line break character «.+?»   
//  Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»   
// Match the character 「"」 literally «"»   


try {   
    Regex regObj = new Regex(@"(\w.+?):""(\w.+?)""");   
    Match matchResults = regObj.Match(sourceString);   
    string[] arr = new string[match.Captures.Count];   
    int i = 0;   
    while (matchResults.Success) {   
     arr[i] = matchResults.Value;   
     matchResults = matchResults.NextMatch();   
     i++;   
    }   
} catch (ArgumentException ex) {   
    // Syntax error in the regular expression   
} 
+0

你複製了RegexBodies的解釋並粘貼在這裏? –

+1

是!我這樣做..... –

+0

我知道,我知道,俚語:d –

1
string[] arr = str.Split(new string[] {"\","}}, StringSplitOptions.None).Select(str => str + "\"").ToArray(); 

被拆分。作爲webnoob提到的\,,然後後綴"使用select,the n轉換爲數組。

+0

好像拆分不能把字符串[]作爲參數 – Jerome

+0

以及如何將一個智能不追加「到最後一個項目中的LINQ – Jerome

+0

@Franklin看到了什麼?我的編輯,我想我錯過了'stringsplitoptions'參數。我不明白你的意思第二個評論? – LukeHennerley

0

最簡單的內置方式是here。我欺騙了它。它工作正常。它拆分到{"Hai","Hello,World"}

相關問題