[英]Applyng expression to ruby search and replace with regexp
我知道在ruby中,您可以使用gsub
和正則表達式搜索和替換字符串。
但是,可以將表達式應用於搜索結果並在替換結果之前進行替換。
例如,在下面的代碼中,盡管可以將匹配的字符串與\\0
一起使用,但是您無法對其應用表達式(例如\\0.to_i * 10
),這樣做會導致錯誤:
shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/\d+/m, \0.to_i * 10)
puts new_list #syntax error, unexpected $undefined
它似乎僅適用於字符串文字:
shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/\d+/m, '\0 string and replace')
puts new_list
這是你想要的嗎?
shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/\d+/m) do |m|
m.to_i * 10
end
puts new_list
# >> 30 apples
# >> 5000g flour
# >> 10 ham
文檔: String#gsub 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.