ruby - Regex Pattern Matching to an array -
i have string defined follows:
st = "the quick {{brown}} fox jumped on {{fence}}." to remove {{ }}, doing following:
st.gsub(/{{(.*?)}}/, '\1') => "the quick brownish fox jumped on fence." what set each of items matched regular look array, end result looks like:
arr = [] puts arr => ['brown', 'fence'] puts st => "the quick brownish fox jumped on fence." thanks in advance.
string#gsub, string#gsub! accepts optional block parameter. homecoming value of block used replacement string.
st = "the quick {{brown}} fox jumped on {{fence}}." arr = [] st.gsub!(/{{(.*?)}}/) { |m| arr << $1; $1 } st # => "the quick brownish fox jumped on fence." arr # => ["brown", "fence"] ruby regex string
No comments:
Post a Comment