将字符串插入正则表达式 [英] Interpolating a string into a regex

查看:40
本文介绍了将字符串插入正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串的值替换为我在 Ruby 中的正则表达式.是否有捷径可寻?例如:

I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:

foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0" 
if goo =~ /value of foo here dynamically/
  puts "success!"
end

推荐答案

同字符串插入.

if goo =~ /#{Regexp.quote(foo)}/
#...

这篇关于将字符串插入正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆