拆分CSV字符串 [英] Split CSV String

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

问题描述

如何分割以下字符串?

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

结果应为

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



<我尝试:

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

但我得到了,

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



感谢

解决方案

如果您有方便的优质图书馆,请手动填写CSV。请!



CSV解析有许多潜在的缺陷,根据我的测试,这个库完全解决了大部分问题。



也就是说,如果这是一个一次性的任务,字符串总是像你的例子,你可以使用regex,像这样(VB.NET语法可能是错误的,请修复):

  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);

这是因为在分隔逗号之后总是有一个空格,逗号之间的数字。如果这不总是这样,你可以:




  • 使正则表达式更复杂(看这里,看看凌乱的东西可以得到什么)

  • 使用图书馆并更快乐。


How would I split the following string?

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

The result should be

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

I try:

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

But I get,

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

Thanks

解决方案

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

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

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:

  • Make the regex more complex (look here to see how messy things could get)
  • Use the library and be happier

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

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