標籤:
# ruby的gsub字串替換功能
1.可以使用hash來替換對應的字串:
"hello 123 world".gsub(/hello|world/, ‘hello‘=>‘HELLO‘, ‘world‘=>‘WORLD‘)# => "HELLO 123 WORLD"
雖然支援第二個參數為hash,但不支援 symbol索引,即 hello: ‘HELLO‘, world: ‘WORLD‘ 無效
"hello 123 world".gsub(/hello|world/, hello: ‘HELLO‘, world: ‘WORLD‘)# => " 123 "
因為沒有找到對應的索引,所以被替換成了Null 字元。
2.可以使用Regex替換字串:
"hello 123 world".gsub /(\d+)/, ‘number‘# => "hello number world"
3.可以使用 \1 \2 \n ... 來引用匹配的子串
"hello 123 world".gsub /(\d+)/, "(\\1)"# => "hello (123) world"
4.可以使用 block來處理匹配內容
"hello 123 world".gsub /(\d+)/ do |m| m.to_i + 1end# => "hello 124 world"
5.多個匹配在block中的引用,無法通過多個block參數引用到,下面的寫法無效:?
"His height is 175.00cm and weight 60.00kg.".gsub /(\d+\.\d+)(\w+)/ do |height, unit| "%g%s" % [height, unit]end
只有第一個參數完整匹配到了 175.00cm,而後面的參數都為nil:height => 175.00cm, unit => nil
正確?寫法:
1.
"His height is 175.00cm and weight 60.00kg.".gsub /(\d+\.\d+)(\w+)/ do |matched| "%g%s" % [$1, $2]end# => "His height is 175cm and weight 60kg."
2.
"His height is 175.00cm and weight 60.00kg.".gsub /(\d+\.\d+)(\w+)/ do |matched| "%g%s" % [Regexp.last_match[1], Regexp.last_match[2]]end# => "His height is 175cm and weight 60kg."
# ruby的gsub字串替換功能