虽然回答得很晚,但发现这个问题很有趣并且投票赞成,因为 IMO 令人惊讶的是,没有内置的方法可以在所描述的条件下保持空白。
因此,假设输入与问题相同,并添加一行以保留双引号转义字符(紧随其后的双引号):
1 , 2
" 1 ", " 2 "
" a ""quoted"" word ", " hello world "
设置HasFieldsEnclosedInQuotes
为 false,并使用简单的处理用引号括起来的任何字段Regex
:
var separator = new string('=', 40);
Console.WriteLine(separator);
// demo only - show the input lines read from a text file
var text = File.ReadAllText(inputPath);
var lines = text.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None
);
using (var textReader = new StringReader(text))
{
using (var parser = new TextFieldParser(textReader))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
parser.TrimWhiteSpace = true;
parser.HasFieldsEnclosedInQuotes = false;
// remove double quotes, since HasFieldsEnclosedInQuotes is false
var regex = new Regex(@"
# match double quote
\""
# if not immediately followed by a double quote
(?!\"")
",
RegexOptions.IgnorePatternWhitespace
);
var rowStart = 0;
while (parser.PeekChars(1) != null)
{
Console.WriteLine(
"row {0}: {1}", parser.LineNumber, lines[rowStart]
);
var fields = parser.ReadFields();
for (int i = 0; i < fields.Length; ++i)
{
Console.WriteLine(
"parsed field[{0}] = [{1}]", i,
regex.Replace(fields[i], "")
);
}
++rowStart;
Console.WriteLine(separator);
}
}
}
输出:
========================================
row 1: 1 , 2
parsed field[0] = [1]
parsed field[1] = [2]
========================================
row 2: " 1 ", " 2 "
parsed field[0] = [ 1 ]
parsed field[1] = [ 2 ]
========================================
row 3: " a ""quoted"" word ", " hello world "
parsed field[0] = [ a "quoted" word ]
parsed field[1] = [ hello world ]
========================================