简体   繁体   English

在字符串中拆分\\“

[英]Splitting on \" in String

So I have this CSV file where it's contents are like so... 所以我有这个CSV文件,它的内容是这样的......

"Name","Age","Gender","City, State"

So far I've been successful at removing the double quotes everywhere - except for the first and last entries with the following code. 到目前为止,我已经成功地删除了双引号 - 除了包含以下代码的第一个和最后一个条目。

using (StreamReader reader = new StreamReader(outputReport))
{
    headers = reader.ReadLine().Split(new string[] { "\",\"" }, 
               StringSplitOptions.RemoveEmptyEntries);
} 

This results in an array of strings with the contents of: 这会产生一个字符串数组,其内容为:

\"Name
Age
Gender
City, State\"

I've made several attempts to remove the \\" 我已多次尝试删除\\"

Including adding this to my split criteria: 包括将此添加到我的拆分条件:

String.Concat('\\','\"')

And this: 和这个:

"\\\""

But nothing seems to work, I feel like I should be able to remove these in the Split method. 但似乎没有任何工作,我觉得我应该能够在Split方法中删除它们。 It's kind of a tricky string to match. 这是一个棘手的字符串匹配。 Any ideas? 有任何想法吗? Thanks for the help! 谢谢您的帮助!

Don't use String.Split() to read CSV data! 不要使用String.Split()来读取CSV数据!

There are too many edge cases. 边缘情况太多了。 You've just hit the tip of the iceberg here. 你刚刚来到冰山一角。 Also, it's much slower than it needs to be. 而且,它比它需要的慢得多。 You want a dedicated CSV parser. 您需要专用的CSV解析器。 There's one built into the framework ( Microsoft.VisualBasic.FileIO.TextFieldParser ), and there are several you can download and use, including FastCSV and my own EasyCSV . 框架内置了一个( Microsoft.VisualBasic.FileIO.TextFieldParser ),有几个可以下载和使用,包括FastCSV和我自己的EasyCSV

try this: s.Replace(@""",","~").Replace(@"""","~").Split('~'); 试试这个: s.Replace(@""",","~").Replace(@"""","~").Split('~'); where s is your string value of a csv line read. 其中s是csv行读取的字符串值。

You may split by characters "(double qoute), '(Comma) and /(Slash). Try this: 您可以按字符“(double qoute),”(逗号)和/(斜杠)分割。试试这个:

        using (StreamReader reader = new StreamReader(outputReport))
        {
            char [] splitByCharSet = new char[3]{'\"', '\\', ','};
            headers = reader.ReadLine().Split(splitByCharSet, StringSplitOptions.RemoveEmptyEntries);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM