我正在检索一个如下所示的字符串:
"[[[256, 498]]] [[[256, 498]], []] [[[256, 498]], [], []] [[[256, 498]], [], [], []]"
怎样才能让它看起来像这样?
[[256,498],[256,498],[],[256,498],[],[],[256,498],[],[],[]]
寻找 ruby 或 JavaScript 解决方案。
最佳答案
仍在寻找更优雅的解决方案,但这会起作用
str.scan(/\[+(\d*, ?\d*)?\]+/).flatten.map do |a|
a ? a.split(",").map(&:to_i) : []
end
#=> [[256, 498], [256, 498], [], [256, 498], [], [], [256, 498], [], [], []]
方法分解
scanned_string_array = str.scan(/\[+(\d*, ?\d*)?\]+/)
#=> [["256, 498"], ["256, 498"], [nil], ["256, 498"], [nil], [nil], ["256, 498"], [nil], [nil], [nil]]
scanned_string_array.flatten
#=> ["256, 498", "256, 498", nil, "256, 498", nil, nil, "256, 498", nil, nil, nil]
scanned_string_array.flatten.map do |a|
#if a is nil return empty array otherwise split on comma and map to Integer
a ? a.split(",").map(&:to_i) : []
end
#=> [[256, 498], [256, 498], [], [256, 498], [], [], [256, 498], [], [], []]
更新:
找到了一种更优雅的方式,或者至少我更喜欢它
str.scan(/\[+(\d*),?\s?(\d*)?\]+/).map do |a|
a.reject(&:empty?).map(&:to_i)
end
#=> [[256, 498], [256, 498], [], [256, 498], [], [], [256, 498], [], [], []]
关于javascript - 如何将这个 ruby 字符串转换为普通数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27806195/