简体   繁体   中英

Applyng expression to ruby search and replace with regexp

I know in ruby you can search and replace a string using gsub and a regular expression.

However is there away to apply an expression to the result of the search and replace before it is replaced.

For example in the code below though you can use the matched string with \\0 you cannot apply expressions to it (eg \\0.to_i * 10 ) and doing so results in an error:

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

It seems to only work with a string literal:

shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST

new_list = shopping_list.gsub(/\d+/m, '\0 string and replace')
puts new_list

Is this what you want?

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

Documentation: String#gsub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM