【发布时间】:2021-01-13 08:54:49
【问题描述】:
我需要执行搜索和替换活动
- "{{content}}" => 替换。 (这是为了保持相同的类型)正则表达式 gsub(/"{{(.*?)}}"/)
- "hello {{content}}" => repalce (this to replace from string) regex gsub(/{{(.*?)}}/)
我构建的方法是
def fill_in(template)
template.gsub(/\"\{\{(.*?)\}\}\"/) do
"test"
end
end
试过 template.gsub(/\"\{\{(.*?)\}\}\"/).gsub(/\{\{(.*?)\}\}/) do 但这是给
我的错误
#
如果第一个 gsub 匹配该模式替换则优先,如果不检查第二个 gsub
template.gsub(/\"\{\{(.*?)\}\}\"/) do
# content will be replaced from the data object
end.gsub(/\"\{\{(.*?)\}\}\"/) do
# content will be replaced from the data object
end
两个 gsub 的 do body 相同,如何停止这种重复
【问题讨论】:
-
错误是什么?你到底想达到什么目的?
-
@WiktorStribiżew 未定义方法 `gsub' for #
-
那你为什么不使用替换字符串呢?
gsub(/.../)将返回一个枚举器,您需要添加'test'作为替换参数。template.gsub(/\"\{\{(.*?)\}\}\"/, "test").gsub(/\{\{(.*?)\}\}/, "test"),见ideone.com/zAXUPD -
@WiktorStribiżew ,我必须使用 do end 因为需要在那里进行复杂的查找
-
在问题中解释你需要什么。
标签: ruby-on-rails regex ruby-on-rails-4