c# - 如何通过引号和逗号开头或结尾的引号进行解析?
问题描述
我的程序从文件中获取一个字符串并将其分成引号,然后分成逗号,引号中的所有逗号都是文本的一部分。
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
解决方案
推荐阅读
- php - 在 codeigniter 中向会话变量添加新值
- android - 如何使用 OpenCV 处理自定义相机拍摄的图片
- lan - 当win pc连接到局域网路由器时停止响应
- reporting-services - ssrs 上的动态图
- go - Golang获取结构字段的字符串名称
- python - 减去数据帧值后恢复索引并附加零
- asp.net - RequestVerificationToken HttpOnly 标志
- sonarqube - 无法运行 SonarQube 6.1、Ubuntu 14、Open Java 1.7.0_111、MySQL 5.7
- android - 触发几个高优先级通知后 Firebase 推送通知延迟
- ios - Swift 中 SpriteKit 的缺点是什么?