【问题标题】:How to use gsub twice?如何使用 gsub 两次?
【发布时间】:2021-01-13 08:54:49
【问题描述】:

我需要执行搜索和替换活动

  1. "{{content}}" => 替换。 (这是为了保持相同的类型)正则表达式 gsub(/"{{(.*?)}}"/)
  2. "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


【解决方案1】:

gsub 只有一个正则表达式作为单个参数来返回一个枚举器,因此您将无法以这种方式链接gsub

您可以将两种模式合二为一:

/(")?\{\{(.*?)\}\}(?(1)"|)/

请参阅regex demo。详情:

  • (")? - 捕获组 1(可选):
  • \{\{ - {{ 文字
  • (.*?) - 捕获组 2:除换行符之外的任何零个或多个字符,尽可能少(如果您也需要匹配换行符,请改用 ((?s:.*?)),或简单地添加 /m 标志)李>
  • \}\} - }} 字符串
  • (?(1)"|) - 一个条件构造:如果组 1 匹配,则匹配 ",否则,匹配一个空字符串。

在代码中,您需要检查组 1 是否匹配,如果匹配,则执行一个替换逻辑,否则,使用另一个替换逻辑。见Ruby demo

def fill_in(template)   
    template.gsub(/(")?\{\{(.*?)\}\}(?(1)"|)/) { 
        $~[1] ? "Replacement 1" : "Replacement 2" 
    }
end

p fill_in('"{{hello}}" and {{hello}}')
# => "Replacement 1 and Replacement 2"

【讨论】:

  • 你能检查一下我在这个ideone.com/3AxiEe中做错了什么吗
  • @KunalVashist 不确定你在做什么,在你的代码中查看what the values are,调试和修复。
  • 所以事情是“{{}}”这个被替换的类型可以改变,“as {{}}”在这种情况下它只是字符串,正则表达式在这种情况下不起作用“ {{test}}我是“
  • 对于“{{user_name}} 是一个 {{user_name}}”我得到 [:"user_name}} 是一个 {{user_name"]
  • $1 也是空的@Wiktor
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多