简体   繁体   中英

How to use gsub twice?

I need to perform to search and replace activity

  1. "{{content}}" => replace. (this to keep same type) regex gsub(/"{{(.*?)}}"/)
  2. "hello {{content}}" => repalce (this to replace from string) regex 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

undefined method `gsub' for #<Enumerator: "{{user_name}}":gsub(/"{{(.*?)}}"/)>

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

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.

You can combine the two patterns into one:

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

See the regex demo . Details:

  • (")? - Capturing group 1 (optional):
  • \{\{ - 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)
  • \}\} - a }} string
  • (?(1)"|) - a conditional construct: if Group 1 matched, match " , else, match an empty string.

In the code, you will need to check if Group 1 matched, and if so, implement one replacement logic, else, use another replacement logic. See the 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"

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