拆分C​​SV字符串 [英] Split CSV String

查看:168
本文介绍了拆分C​​SV字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何分割以下字符串?

How would I split the following string?

test, 7535, '1,830,000', '5,000,000'

结果应该是

test
7535
'1,830,000'
'5,000,000'

我尝试:

Dim S() as string = mystring.split(",")

但我得到的,

But I get,

test
7535
'1
830
000'
'5
000
000'

感谢

推荐答案

不要手动解析CSV,当你有方便的优良的品质库提供。请!

Don't parse CSV manually when you have handy good quality libraries available. Please!

CSV解析有很多很多潜在的隐患和这个库,根据我的测试,解决了大部分整齐。

CSV parsing has many many potential pitfalls and this library, according to my testing, solves most of them neatly.

这是说,如果这是一个一次性的任务,而弦乐总是喜欢你的例子,你可以使用正则表达式,像这样(VB.NET语法可能是错误的,请修正):

That said, if this is a one off task and the strings are always like your example, you can use regex, like this (VB.NET syntax might be wrong, please fix):

        Dim s as string = "1, 2, '1,233,333', '8,444,555'";
        Dim r as Regex = new Regex(",\s");
        Dim re() as string = r.Split(s);

此计数上总是有分离逗号后的空间,并且有在数字之间的逗号没有空间。如果是这样的情况并非总是如此,你可以:

This counts on that there is always a space after the separating comma and that there is no space in the commas between the numbers. If that's not always the case you can:

  • 请正则表达式更复杂(看看<一href="http://stackoverflow.com/questions/809156/net-system-outofmemoryexception-on-string-split-of-120-mb-csv-file">here怎么看乱七八糟的东西能拿)
  • 使用图书馆和快乐
  • Make the regex more complex (look here to see how messy things could get)
  • Use the library and be happier

这篇关于拆分C​​SV字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆