分裂相关的功能

时间:2011-03-30 20:09:00

标签: ruby regex iterator

我使用ruby 1.9.2。

gsub / scan将匹配迭代到给定的正则表达式/字符串,并以三种方式使用:

  1. 如果在没有块的情况下使用scan,则返回一个匹配数组。
  2. 如果scan与块一起使用,它会迭代匹配并执行某些操作。
  3. 如果使用gsub,则将匹配替换为第二个参数或块的匹配,并返回一个字符串。
  4. 另一方面,splitgsub / scan匹配的补码相匹配。但是,只有一种方法可以使用它:

    1. 如果在没有块的情况下使用split,它将返回匹配补充的数组。
    2. 我希望其他两个与split相关的缺失用法,并尝试实现它们。以下every_other扩展了split,因此可以像scan一样使用。

      class String
        def every_other arg, &pr
          pr ? split(arg).to_enum.each{|e| pr.call(e)} : split(arg)
        end
      end
      
      # usage:
      'cat, two dogs, horse, three cows'.every_other(/,\s*/) #=> array
      'cat, two dogs, horse, three cows'.every_other(/,\s*/){|s| p s} # => executes the block
      

      然后,我试图实现gsub的对应物,但不能做得好。

      class String
        def gsub_other arg, rep = nil, &pr
          gsub(/.*?(?=#{arg}|\z)/, *rep, &pr)
        end
      end
      
      # usage
      'cat, two dogs, horse, three cows'.gsub_other(/,\s*/, '[\1]') # or
      'cat, two dogs, horse, three cows'.gsub_other(/,\s*/) {|s| "[#{s}]"}
      
      # Expected => "[cat], [two dogs], [horse], [three cows]"
      # Actual output => "[cat][],[ two dogs][],[ horse][],[ three cows][]"
      
      • 我做错了什么?
      • 这种做法是否正确?有没有更好的方法,或者已经有方法可以做到这一点?
      • 您对方法名称有什么建议吗?

1 个答案:

答案 0 :(得分:0)

它不漂亮,但这似乎有效

s='cat, two dogs, horse, three cows'
deli=",\s"
s.gsub(/(.*?)(#{deli})/, '[\1]\2').gsub(/(.*\]#{deli})(.*)/, '\1[\2]')

=> "[cat], [two dogs], [horse], [three cows]"

以下感觉好一点

s.split(/(#{deli})/).map{|s| s!=deli ? "[#{s}]" : deli}.join