2

I'm trying to split the string "[test| blah] [foo |bar][test|abc]" into the following array:

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

But I'm have trouble getting my regular expression right.


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

I'm not quite there, this returns:

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

What would be the correct regular expression to achieve this? It would be great if I could also account for new lines, say: "[test| blah] \n [foo |bar]\n[test|abc]"

4

2 回答 2

8

Better to use String#scan for this:

> "[test| blah] \n [foo |bar]\n[test|abc]".scan(/\[(.*?)\s*\|\s*(.*?)\]/)
=> [["test", "blah"], ["foo", "bar"], ["test", "abc"]]
于 2013-03-30T12:49:59.997 回答
1

Here is another sample:

'[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"]]
于 2013-03-30T12:54:55.173 回答