正则表达式。从字符串中获取字段

时间:2014-09-23 19:38:19

标签: c# regex string

我无法编写正则表达式模式

的字符串:

25,4.6,4%,32,"text1","text2, text3","text4,,t"

结果数组:

25 |
4.6 |
4% |
32 |
"text1" |
"text2, text3" |
"text4,,t" |

2 个答案:

答案 0 :(得分:1)

我不会使用正则表达式(或String.Split)来解析CSV,而是使用可用的csv-parser。 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

答案 1 :(得分:0)

RegEx不是这种方法,因为它不能很好地处理引用的字符串(或平衡paranthesis)。

但是,您的数据看起来像是CSV。如果是这样,.NET有TextFieldParser解析CSV(包括引号)。

您必须在项目中添加对Microsoft.VisualBasic的引用才能使用此功能。

使用C#和引用值查看this SO question示例。