繁体   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