c# - 忽略双引号内的 Rogue 引号

标签 c# .net string

我有以下用于 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/

相关文章:

c# - 如何开始使用 Google API v3?

c# - volatile 是避免 C# 中竞争条件的好做法吗?

c# - 如何提高EF中查询的执行速度

c# - 使用 MonoDroid C# 显示状态栏通知

.net - 为什么 .NET app.config 加载规则与 win2k3 不同?

c# - 调用lambda时 "DisplayClass"name是什么意思?

.net - DynamoDB 新手。有没有更方便的方法来添加/放置项目?

c - 在C中的函数中打印数组中的字符串

c# - 在字边界上将字符串拆分为 2 个字符串以最小化长度差异的优雅方法

c - 我是否需要在 for 循环中使用 strcat 检查目标字符串长度