简体   繁体   English

如何使用 gsub 两次?

[英]How to use gsub twice?

I need to perform to search and replace activity我需要执行搜索和替换活动

  1. "{{content}}" => replace. "{{content}}" => 替换。 (this to keep same type) regex gsub(/"{{(.*?)}}"/) (这是为了保持相同的类型)正则表达式 gsub(/"{{(.*?)}}"/)
  2. "hello {{content}}" => repalce (this to replace from string) regex gsub(/{{(.*?)}}/) "hello {{content}}" => repalce(从字符串替换)正则表达式 gsub(/{{(.*?)}}/)

Method that i build is我建立的方法是

def fill_in(template)   
      template.gsub(/\"\{\{(.*?)\}\}\"/) do
        "test"   
      end 
end

Tried template.gsub(/\"\{\{(.*?)\}\}\"/).gsub(/\{\{(.*?)\}\}/) do but this is giving me error试过template.gsub(/\"\{\{(.*?)\}\}\"/).gsub(/\{\{(.*?)\}\}/) do ,但这给了我错误

undefined method `gsub' for #<Enumerator: "{{user_name}}":gsub(/"{{(.*?)}}"/)> #<Enumerator: "{{user_name}}":gsub(/"{{(.*?)}}"/)> 的未定义方法 `gsub'

first gsub is priority if it matches that pattern replace based on then if not check for second gsub如果第一个 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

do body for both gsub is same, how to stop this repetition两个 gsub 的 do body 是相同的,如何停止这种重复

Thegsub with just a regex as a single argument to return an Enumerator , so you won't be able to chain the gsub in this way. gsub仅将正则表达式作为返回Enumerator的单个参数,因此您无法以这种方式链接gsub

You can combine the two patterns into one:您可以将两种模式合二为一:

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

See the regex demo .请参阅正则表达式演示 Details:细节:

  • (")? - Capturing group 1 (optional): (")? - 捕获第 1 组(可选):
  • \{\{ - a {{ text \{\{ - {{文本
  • (.*?) - Capturing group 2: any zero or more chars other than line break chars, as few as possible (if you need to match line breaks, too, use ((?s:.*?)) instead, or simply add /m flag) (.*?) - 捕获第 2 组:除换行符以外的任何零个或多个字符,尽可能少(如果您也需要匹配换行符,请改用((?s:.*?)) ,或者只需添加/m标志)
  • \}\} - a }} string \}\} - }}字符串
  • (?(1)"|) - a conditional construct: if Group 1 matched, match " , else, match an empty string. (?(1)"|) - 条件构造:如果第 1 组匹配,则匹配" ,否则匹配空字符串。

In the code, you will need to check if Group 1 matched, and if so, implement one replacement logic, else, use another replacement logic.在代码中,您需要检查第 1 组是否匹配,如果匹配,则执行一个替换逻辑,否则,使用另一个替换逻辑。 See the Ruby demo :请参阅Ruby 演示

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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