【发布时间】:2013-08-08 08:16:37
【问题描述】:
我有以下用于 csv 解析器的代码
string input = wholeFile;
IList<string> wholeFileArray = new List<string>();
int start = 0;
bool inQuotes = false;
for (int current = 0; current < input.Length; current++)
{
// test each character before and after to determine if it is a valid quote, or a quote within a quote.
int test_backward = (current == 0 ? 1 : current) - 1;
int test_forward = (current == input.Length - 1 ? input.Length - 2 : current) + 1;
bool valid_quote = input[test_backward] == ',' || input[test_forward] == ',' || input[test_forward] == '\r';
if (input[current] == '\"') // toggle state
{
inQuotes = !inQuotes;
}
bool atLastChar = (current == input.Length - 1);
if (atLastChar)
{
wholeFileArray.Add(input.Substring(start));
}
else if (input[current] == ',' && !inQuotes)
{
wholeFileArray.Add(input.Substring(start, current - start));
start = current + 1;
}
}
如果, 不在这样的双引号"something,foobar" 字符串内,它会接受一个字符串并将其拆分到,。
我的问题是我的字符串中的流氓" 正在搞乱我的整个过程。
例如:"bla bla","bla bla2",3,4,"5","bla"bla","End"
结果
- “bla bla”
- "bla bla2"
- 3
- 4
- “5”
- "bla"bla","End"
如何更改我的代码以允许流氓"
“有效”右引号后始终跟逗号 (,) 或控制换行符
已添加 这似乎解决了它
// test each character before and after to determine if it is a valid quote, or a quote within a quote.
int test_backward = (current == 0 ? 1 : current) - 1;
int test_forward = (current == input.Length - 1 ? input.Length - 2 : current) + 1;
bool valid_quote = input[test_backward] == ',' || input[test_forward] == ',' || input[test_forward] == '\r';
【问题讨论】:
-
就像尝试确定黑白引号时的颜色一样有趣,我决定更正拼写。
-
您的示例中唯一可靠的模式是“有效”右引号后始终跟逗号 (
,)。你也许可以通过检查来让它工作 -
@musefan 我应该提到这是一个 csv 解析器,所以它也需要在行尾匹配
-
@Josefvz:问题是输入无效。没有人可以期望解析器只处理无效数据。内部引号应该被转义。你能做的最好的事情就是像我说的那样,在每个潜在的关闭引号之后,向前看几个字符,然后确定你是否仍然在一个字符串中。即,如果您在可能关闭的引号和下一个引号(或行尾)之间只有一个逗号或空格,那么它就是一个有效的关闭引号。如果您发现任何其他字符,假设您仍在字符串中。
-
明天你会回来对我们说...我有双重流氓:
"bla",bla"...我该怎么办?