我有以下用于 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"
字符串中,它接受一个字符串并在 ,
上拆分它.
我的问题是字符串中的流氓 "
弄乱了我的整个过程。
EX: "bla bla","bla bla2",3,4,"5","bla"bla","End"
结果
- “啦啦啦”
- “bla bla2”
- 3
- 4
- “5”
- "bla"bla","结束"
如何更改我的代码以允许流氓 "
“有效”的右引号后面始终跟有逗号 (,) 或控制换行符
已添加 这似乎可以解决问题
// 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] == '"' && // 1
(!inQuotes || // 2
current + 1 == input.Length || // 3
input[current + 1] == '\r' || // 4
input[current + 1] == '\n' || // 5
(input[current + 1] == ',' && // 6
(current + 2 == input.Length || // 7
input[current + 2] == '\r' || // 8
input[current + 2] == '\n' || // 9
input[current + 2] == '"' || // 10
(input[current + 2] >= '0' && input[current + 2] <= '9'))))) // 11
// toggle state
但请注意,您想要做的事情在各种概念层面上都是错误的。
正确的引号是开头引号 2 或字符串 3 的最后一个字符或后跟 \r
的引号4 或 \n
5 或后面跟一个 ,
6 依次是字符串 7 的最后一个字符或后跟一个 \r
8 或 \n
9 或引用 "
10 或按数字 11。
关于c# - 忽略双引号内的 Rogue 引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18121116/