正则表达式应该拆分,包含在CSV文件中的双引号之外?

这是样本

"abc","abcsds","adbc,ds","abc" 

输出应该是

 abc abcsds adbc,ds abc 

试试这个:

 "(.*?)" 

如果你需要把这个正则表达式放在文字中,不要忘记逃避它:

 Regex re = new Regex("\"(.*?)\""); 

这比你意识到的更艰巨 – 不仅引号内可以有逗号,而且引号内也可以有引号。 带引号的字符串中的两个连续引号不表示字符串的结尾。 相反,它表示嵌入在字符串中的引用,例如:

 "x", "y,""z""" 

应解析为:

 x y,"z" 

所以,基本序列是这样的:

 Find the first non-white-space character. If it was a quote, read up to the next quote. Then read the next character. Repeat until that next character is not also a quote. If the next (non-whitespace) character is not a comma, input is malformed. If it was not a quote, read up to the next comma. Skip the comma, repeat the whole process for the next field. 

请注意,尽管有标记,但我没有提供正则表达式 – 我完全不确定我是否已经看到了可以正确处理这一问题的正则表达式。

这个答案有一个用于处理CSV的C#解决方案。

特别是这条线

 private static Regex rexCsvSplitter = new Regex( @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))" ); 

包含用于正确拆分的正则表达式,即考虑引用和转义。

基本上它所说的是,匹配任何后跟偶数引号(包括零)的逗号。 这有效地防止了匹配作为引用字符串一部分的逗号,因为引号字符通过加倍来转义。

请记住,为了字符串文字,上面一行中的引号加倍。 将表达式视为可能更容易

 ,(?=(?:[^"]*"[^"]*")*(?![^"]*")) 

如果你可以确定没有内部的,转义的引号,那么我可以使用正则表达式。 但是,大多数现代语言已经具有适当的CSV解析器。

使用正确的解析器是正确的答案。 例如, Text::CSV for Perl。

但是,如果你已经开始使用正则表达式了,我建议你从某种模块“借用”,比如这个: http : //metacpan.org/pod/Regexp :: Common :::