Ruby .split()正则表达式

我正在尝试将字符串"[test| blah] [foo |bar][test|abc]"拆分为以下数组:

 [ ["test","blah"] ["foo","bar"] ["test","abc"] ] 

但我无法正确表达我的正则表达式。


ruby:

 @test = '[test| blah] [foo |bar][test|abc]'.split(%r{\s*\]\s*\[\s*}) @test.each_with_index do |test, i| @test[i] = test.split(%r{\s*\|\s*}) end 

我不在那里,这回来了:

 [ [ "[test" , "blah" ] [ "foo" , "bar" ] [ "test" , "abc]" ] ] 

实现这一目标的正确正则表达式是什么? 如果我还可以考虑新行,那就太好了,比如说: "[test| blah] \n [foo |bar]\n[test|abc]"

最好使用String#scan进行此操作:

 > "[test| blah] \n [foo |bar]\n[test|abc]".scan(/\[(.*?)\s*\|\s*(.*?)\]/) => [["test", "blah"], ["foo", "bar"], ["test", "abc"]] 

这是另一个例子:

 '[test| blah] [foo |bar][test|abc]'.scan(/\w+/).each_slice(2).to_a #=> [["test", "blah"], ["foo", "bar"], ["test", "abc"]] "[test| blah] \n [foo |bar]\n[test|abc]".scan(/\w+/).each_slice(2).to_a #=> [["test", "blah"], ["foo", "bar"], ["test", "abc"]]