2014-10-26 68 views
0

我有一個字符串定義如下:正則表達式匹配到一個數組

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." 

謝謝萬斯。

回答

3

String#gsub,String#gsub!接受可選的塊參數。塊的返回值用作替換字符串。

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"] 
+0

不能接受這個答案10分鐘,但是這就是答案,它在我的IRB工作正常。很快會接受:-)謝謝! – 2014-10-26 14:08:24

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

@CarySwoveland是的。你是對的。我第一次擁有它,然後以某種方式刪除它。我錯了。 – sawa 2014-10-26 18:56:33