[英]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. 鉴于像一个字符串
"this is the {{any}} string"
,我想gsub
(或类似) {{any}}
与/.*/
,然后使用整个字符串作为我的匹配。
I've tried, as you could guess, "this is the {{any}} string".gsub("{{any}}", /.*/)
, which gives the error: 您已经猜到,我已经尝试过
"this is the {{any}} string".gsub("{{any}}", /.*/)
,它给出了错误:
TypeError: no implicit conversion of Regexp into String
TypeError:没有将Regexp隐式转换为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 Regexp.quote
对字符串进行转义,使其与逐字匹配 gsub
replaces {{any}}
, which is by now escaped, with .*
gsub
将{{any}}
替换为.*
Regexp.new
creates a regexp Regexp.new
创建一个正则表达式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.