【问题标题】:Ruby .split() Regular ExpressionRuby .split() 正则表达式
【发布时间】:2013-03-30 12:45:53
【问题描述】:

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

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

但我无法正确使用正则表达式。


鲁比:

@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]"

【问题讨论】:

    标签: ruby-on-rails ruby regex string split


    【解决方案1】:

    最好使用String#scan

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

    【讨论】:

      【解决方案2】:

      这是另一个示例:

      '[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"]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-06
        • 2012-05-28
        • 1970-01-01
        • 2012-10-17
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2012-05-01
        相关资源
        最近更新 更多