Ruby映射嵌套数组

时间:2013-03-31 14:44:35

标签: ruby regex arrays map

我有这个字符串,我正在尝试拆分成嵌套数组:

x = '{type:paragaph|class:red|content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]}'
x << '{type:image|class:grid|content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]}'

到目前为止:

x.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}

成功地将其划分为:

[
  ["type:paragaph", "class:red", "content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]"],
  ["type:image", "class:grid", "content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]"]
]

我正在尝试添加其他地图:

x.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}.map {|m| m[0].split(/\:\s*(?=[^\[\]]*(?:\[|$))/)}

返回:

[["type", "paragaph"], ["type", "image"]] 

然而我在此之后:

[
  [['type','paragaph'], ['class','red'], ['content',['[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]']],
  [['type','image'], ['class','grid'], ['content','[id:1|title:image1][id:2|title:image2][id:3|title:image3]']]
]

地图似乎将自己应用于整个第二级数组而不是其中的每个元素。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

在第二张地图中,您只拆分第一个元素,而不是用地图分割每个元素

x.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}.map {|m| m.map {|n| n.split(/\:\s*(?=[^\[\]]*(?:\[|$))/)}}

此外,您可以将其清理一下,将正则表达式提取为变量

regex = /\|\s*(?=[^\[\]]*(?:\[|$))/

x.scan(/\{(.*?)\}/).map {|m| m[0].split(regex)}.map {|m| m.map {|n| n.split(regex)}}