正则表达式分割线(csv文件)

sha*_*esh 8 .net c# regex csv

我在正则表达式方面不擅长.有人可以帮我写出正则表达式吗?

在阅读csv文件时,我可能有这样的值.

"Artist,Name",Album,12-SCS
"val""u,e1",value2,value3

输出:

Artist,Name  
Album
12-SCS
Val"u,e1 
Value2 
Value3

更新:我喜欢使用Oledb提供商的想法.我们在网页上有文件上传控制,我使用流阅读器读取文件的内容,而文件系统上没有实际的保存文件.有没有办法我可以使用Oledb提供程序,因为我们需要在连接字符串中指定文件名,在我的情况下,我没有在文件系统上保存文件.

Jos*_*hua 14

只需添加我今天早上工作的解决方案.

var regex = new Regex("(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");

foreach (Match m in regex.Matches("<-- input line -->"))
{
    var s = m.Value; 
}
Run Code Online (Sandbox Code Playgroud)

如您所见,您需要每行调用regex.Matches().然后它将返回一个MatchCollection,其具有与列相同数量的项目.显然,每个匹配的Value属性是已解析的值.

这仍然是一项正在进行中的工作,但它很乐意解析CSV字符串,如:

2,3.03,"Hello, my name is ""Joshua""",A,B,C,,,D
Run Code Online (Sandbox Code Playgroud)


rid*_*ner 8

实际上,它很容易匹配CVS线与正则表达式.试试这个:

StringCollection resultList = new StringCollection();
try {
    Regex pattern = new Regex(@"
        # Parse CVS line. Capture next value in named group: 'val'
        \s*                      # Ignore leading whitespace.
        (?:                      # Group of value alternatives.
          ""                     # Either a double quoted string,
          (?<val>                # Capture contents between quotes.
            [^""]*(""""[^""]*)*  # Zero or more non-quotes, allowing 
          )                      # doubled "" quotes within string.
          ""\s*                  # Ignore whitespace following quote.
        |  (?<val>[^,]*)         # Or... zero or more non-commas.
        )                        # End value alternatives group.
        (?:,|$)                  # Match end is comma or EOS", 
        RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
    Match matchResult = pattern.Match(subjectString);
    while (matchResult.Success) {
        resultList.Add(matchResult.Groups["val"].Value);
        matchResult = matchResult.NextMatch();
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
Run Code Online (Sandbox Code Playgroud)

免责声明:正则表达式已在RegexBuddy中测试过(生成此片段),并且它正确匹配OP测试数据,但C#代码逻辑未经测试.(我无法访问C#工具.)


Bal*_*usC 6

正则表达式不适合这个.使用CSV 解析器.无论是内置的还是第三方的.


Bri*_*iec 5

TextFieldParser类看一下.它位于Microsoft.VisualBasic程序集中,并进行分隔和固定宽度解析.


Wil*_*l A -1

正则表达式在这里可能会变得过于复杂。用逗号分割该行,然后迭代结果位并将它们连接到“连接字符串中双引号的数量”不均匀的位置。

“你好,这个”,是“一个“测试””

...分裂...

“你好|这个”| 是 | “一个测试”””

...迭代并合并,直到双引号的数量为偶数...

“hello,this” - 偶数引号(注意逗号被插入位之间的分割删除)

is - 偶数个引号

"a ""test""" - 偶数个引号

...然后删除前导和尾随引号(如果存在)并将“”替换为“。