开发者

Ruby: Is there a way to split a string only with the first x occurrencies?

For example, suppose I have this:

001, "john doe", "male", 37, "programmer", "likes dogs, women, and is lazy"

The problem is that the line is only supposed to have 6 fields. But if I separate it with split I get more, due to the comma being used improperly to separate the fields.

Right now I'm splitting everything, then when I get to the 5-th index onward I concatenate all the strings. But I w开发者_高级运维as wondering if there was a split(",",6) or something along these lines.


Ruby has a CSV module in the standard library. It will do what you really need here (ignore commas in doubles quotes).

require 'CSV.rb'
CSV::Reader.parse("\"cake, pie\", bacon") do |row| p row; end

result:

["cake, pie", " bacon"]
=> nil

You might want to strip the results if you're dim like me and stick whitespace everywhere.


Yes, you can do the_string.split(",", 6). However this will still give "wrong" result if there's a comma inside quotes somewhere in the middle (e.g. 001, "doe, john",...).

However using Shellwords might be more appropriate here as this will also allow other sections than the last to contain commas inside quotes (it will also remove the quotes which may or may not be a problem, depending on what you're trying to do).

Example:

require 'shellwords'
the_string = %(001, "doe, john", "male", 37, "programmer", "likes dogs, women, and is lazy")
Shellwords.shellwords the_string
#=> ["001,", "doe, john,", "male,", "37,", "programmer,", "likes dogs, women, and is lazy"]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜