简体   繁体   中英

gsub regex into a string

Given a string like "this is the {{any}} string" , I'd like to gsub (or similar) {{any}} with /.*/ and then use that entire string as my matcher.

I've tried, as you could guess, "this is the {{any}} string".gsub("{{any}}", /.*/) , which gives the error:

TypeError: no implicit conversion of Regexp into String

Try this

string = "this is the {{any}} string"
regexp = Regexp.new(Regexp.quote(string).gsub("\\{\\{any\\}\\}", '.*'))

How does this work?

  • Regexp.quote escapes the string such that it matches verbatim
  • gsub replaces {{any}} , which is by now escaped, with .*
  • Regexp.new creates a regexp

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