我使用ruby 1.9.2。
gsub
/ scan
将匹配迭代到给定的正则表达式/字符串,并以三种方式使用:
scan
,则返回一个匹配数组。scan
与块一起使用,它会迭代匹配并执行某些操作。gsub
,则将匹配替换为第二个参数或块的匹配,并返回一个字符串。另一方面,split
与gsub
/ scan
匹配的补码相匹配。但是,只有一种方法可以使用它:
split
,它将返回匹配补充的数组。我希望其他两个与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][]"
答案 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