希望将数据字符串(参数)拆分为数组,但对此有一些特定的条件。我拥有的字符串如下所示:
cyr_ad_id\tproject_number\tname\tremote_reference\tsample_size\tad_length\tsample_description\tmedia_type\tnotes\r\n13342a\t13342\tMore Dad_BC\t2897855894001\t150\t:30\t50% Customers\r\n50% Non-customers\tFilm\tBroadcast\r\n13342c\t13342\tDRTV - Hogs\t2897815438001\t150\t:60\t100% Non-customers\tFilm\tBroadcast\r\n13342d\t13342\tMake Way For More\t2897815439001\t150\t:30\t50% Customers\r\n50% Non-customers\tFilm\tBroadcast\r\n我希望得到以下结果:
["cyr_ad_id\tproject_number\tname\tremote_reference\tsample_size\tad_length\tsample_description\tmedia_type\tnotes", "13342a\t13342\tMore Dad_BC\t2897855894001\t150\t:30\t50% Customers\r\n50% Non-customers\tFilm\tBroadcast", "13342c\t13342\tDRTV - Hogs\t2897815438001\t150\t:60\t100% Non-customers\tFilm\tBroadcast", "13342d\t13342\tMake Way For More\t2897815439001\t150\t:30\t50% Customers\r\n50% Non-customers\tFilm\tBroadcast"]我觉得我需要做的是类似于在第8次出现“t”之后将字符串拆分为"\r\n“。第八次出现的是我希望通过变量传递到拆分语句中的内容。
有一些可能出现的"\r\n“事件,我不想将该字符串拆分,因此在本例中,第n或第8次出现的”t“非常重要。
谢谢!
发布于 2013-12-13 02:35:08
这符合你的需要吗?
def ssplit str, n
r = Regexp.new "([^\t]*?\t){#{n}}(.*?\r\n)"
matched = []
while s = str.slice!(r) do
matched << s.strip
end
matched
end发布于 2013-12-13 03:00:45
your_string.gsub("\r\n", "\t").gsub("\n", '').split("\t").each_slice(8).to_a
将所有\r\n替换为\t,然后杀死\n上遗留的任何一个。在\t上拆分。现在您有了一个项目数组。
您也可以使用regex,我似乎无法使用regex。.split(/\\r|\\t|\\n/)
.each_slice(8).to_a一次接受8个项,并将它们重新构建起来,因此每个组都有一个数组。
您也可以做.in_groups_of(8)而不是.each_slice。因此,也不需要.to_a。
[["cyr_ad_id", "project_number", "name", "remote_reference", "sample_size", "ad_length", "sample_description", "media_type"], ["notes", "13342a", "13342", "More Dad_BC", "2897855894001", "150", ":30", "50% Customers"], ["50% Non-customers", "Film", "Broadcast", "13342c", "13342", "DRTV - Hogs", "2897815438001", "150"], [":60", "100% Non-customers", "Film", "Broadcast", "13342d", "13342", "Make Way For More", "2897815439001"], ["150", ":30", "50% Customers", "50% Non-customers", "Film", "Broadcast"]]那似乎更有用?
https://stackoverflow.com/questions/20557164
复制相似问题