首页 > 解决方案 > 如何通过引号和逗号开头或结尾的引号进行解析?

问题描述

我的程序从文件中获取一个字符串并将其分成引号,然后分成逗号,引号中的所有逗号都是文本的一部分。

static void Main(string[] args)
    {
        string[] source = File.ReadAllLines("file.csv", Encoding.Default);

        string src = source[0];

        //text preparation for spliting
        string modifiedSrc = src.Replace("\",", "\"").Replace(", \"", "\"");

        List<string> data = new List<string>();
        string [] parts = modifiedSrc.Split('\"');

        //odd elements separated by quotes, even by commas
        data.AddRange(parts.Where((x, index) => index % 2 != 0));
        data.AddRange(parts.Where((x, index) => index % 2 == 0).SelectMany(x => x.Split(',')));
        string result = string.Join(" | ", data.Where(x => !string.IsNullOrWhiteSpace(x)));
        Console.WriteLine(result);

        Console.ReadKey();
    }

文本:猫,狗,“大,蛇”,狼
将显示:猫| 狗 | 大蛇| 高分辨率照片| CLIPARTO 狼

text: cat, dog, "big, snake", human, "wild, wolf"
将显示:cat | 狗 | 大蛇| 高分辨率照片| CLIPARTO 人类 | 野生, 狼

但是,如果引号中只有一个文本,并且在末尾或开头不正确:
text: "big, cat", dog, human
将显示: big, cat | 狗,人类

狗,人类未分享于:狗 | 人类

如何解决这种特殊情况?我被禁止使用图书馆一侧。

CSV 文件https://drive.google.com/file/d/1DtjK6LcI0KLY7B59wD_KkFP3KxZadm5-/view?usp=sharing

标签: c#.net

解决方案


推荐阅读