領域,我不能寫一個正則表達式模式正則表達式模式。獲得從字符串
字符串:
25,4.6,4%,32,"text1","text2, text3","text4,,t"
結果數組:
25 |
4.6 |
4% |
32 |
"text1" |
"text2, text3" |
"text4,,t" |
領域,我不能寫一個正則表達式模式正則表達式模式。獲得從字符串
字符串:
25,4.6,4%,32,"text1","text2, text3","text4,,t"
結果數組:
25 |
4.6 |
4% |
32 |
"text1" |
"text2, text3" |
"text4,,t" |
正則表達式是不走這一點,因爲它不是」的方式t旨在很好地處理引用的字符串(或平衡paranthesis)。
但是,它看起來像您的數據是CSV。如果這是真的,.NET有一個TextFieldParser解析CSV(包括引號)。
您必須在項目中添加對Microsoft.VisualBasic
的引用才能使用它。
查看this SO question查看使用C#和引用值的示例。
我不會使用正則表達式(或String.Split
)來解析CSV,但是可用的csv解析器。 TextFieldParser
是已經內置.NET的唯一解析器。你也可以用它在C#:
string csv = "25,4.6,4%,32,\"text1\",\"text2, text3\",\"text4,,t\"";
var reader = new StringReader(csv);
List<string[]> allLineFields = new List<string[]>();
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))
{
parser.Delimiters = new string[] { "," };
parser.TrimWhiteSpace = true;
parser.HasFieldsEnclosedInQuotes = true; // <--- !!!
string[] fields;
while ((fields = parser.ReadFields()) != null)
{
allLineFields.Add(fields);
}
}
foreach (string[] arr in allLineFields)
Console.WriteLine(string.Join("|", arr));
輸出:25|4.6|4%|32|text1|text2, text3|text4,,t
當然也有這樣的其他現有的解析器:A Fast CSV Reader
爲您處理引用正則表達式不會幫助你在這裏字符串,你需要編寫一個狀態機解析器。 – Dai 2014-09-23 19:40:50
我在這裏回答了一個類似的問題:http://stackoverflow.com/questions/4403194/split-using-delimiter-except-when-delimiter-is-escaped – juharr 2014-09-23 19:50:47
[停止滾動你自己的CSV解析器](http:// secretgeek達網絡/ csv_trouble) – 2014-09-23 19:58:28