正则表达式模式匹配到数组

时间:2014-10-26 14:03:28

标签: ruby regex string

我的字符串定义如下:

st = "The quick {{brown}} fox jumped over the {{fence}}." 

要删除{{}},我正在执行以下操作:

st.gsub(/{{(.*?)}}/, '\1') 
=> "The quick brown fox jumped over the fence." 

我现在要做的是将与正则表达式匹配的每个项目放入一个数组中,以便最终结果如下所示:

arr = []
puts arr => ['brown', 'fence']
puts st => "The quick brown fox jumped over the fence." 

提前致谢。

2 个答案:

答案 0 :(得分:3)

String#gsubString#gsub!接受可选的block参数。块的返回值用作替换字符串。

st = "The quick {{brown}} fox jumped over the {{fence}}."
arr = []
st.gsub!(/{{(.*?)}}/) { |m| arr << $1; $1 }
st
# => "The quick brown fox jumped over the fence."
arr
# => ["brown", "fence"]

答案 1 :(得分:2)

st.gsub!(/{{(.*?)}}/).with_object([]){|_, a| a.push($1); $1} #=> ["brown", "fence"]
st #=> "The quick brown fox jumped over the fence."