[英]Ruby: Is there a way to split a string only with the first x occurrencies?
例如,假设我有这个:
001, "john doe", "male", 37, "programmer", "likes dogs, women, and is lazy"
问题是该行只应该有6个字段。 但是,如果我将它与split分开,我会得到更多,因为逗号被不正确地用于分隔字段。
现在我正在拆分所有东西,然后当我到达第5个索引时,我连接所有的字符串。 但我想知道是否存在分裂(“,”,6)或沿着这些方向的东西。
是的,你可以做the_string.split(",", 6)
。 但是,如果在中间某处有引号内的逗号(例如001, "doe, john",...
) 001, "doe, john",...
这仍然会给出“错误”的结果。
但是在这里使用Shellwords可能更合适,因为这也允许除了last之外的其他部分在引号内包含逗号(它也会删除引号,这可能是也可能不是问题,具体取决于你要做的事情)。
例:
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.