Tom
Tom

Reputation: 2230

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

Upvotes: 1

Views: 622

Answers (1)

akuhn
akuhn

Reputation: 27793

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

Upvotes: 2

Related Questions