簡體   English   中英

將表達式應用於ruby搜索並用正則表達式替換

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM