将字符串插入正则表达式

我需要在 Ruby 的正则表达式中替换字符串的值。有什么简单的方法吗?例如:

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
57917 次浏览

使用 Regexp.new:

if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/

可能 Regexp.escape(foo)将是一个起点,但是有一个好的理由,你不能使用更传统的表达式-插值: "my stuff #{mysubstitutionvariable}"

另外,您可以只使用字符串 !goo.match(foo).nil?

Regexp.compile(Regexp.escape(foo))

和字符串插入一样。

if goo =~ /#{Regexp.quote(foo)}/
#...
foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0"


puts "success!" if goo =~ /#{foo}/

请注意,Jon L. 的回答中的 Regexp.quote非常重要!

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

如果你只是做“显而易见”的版本:

if goo =~ /#{foo}/

然后将匹配文本中的句点作为 regexp 通配符处理,"0.0.0.0"将匹配 "0a0b0c0"

另请注意,如果您真的只是想检查子字符串匹配,那么您可以简单地这样做

if goo.include?(foo)

它不需要额外的引用或担心特殊字符。

这里有一个有限但有用的其他答案:

我发现,如果我只在输入字符串上使用单引号(IP 地址匹配) ,就可以很容易地在不使用 Regexp.quote 或 Regexp.escape 的情况下插入正则表达式

IP_REGEX = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'


my_str = "192.0.89.234 blahblah text 1.2, 1.4" # get the first ssh key
# replace the ip, for demonstration
my_str.gsub!(/#{IP_REGEX}/,"192.0.2.0")
puts my_str # "192.0.2.0 blahblah text 1.2, 1.4"

单引号只能解释和’。

Http://en.wikibooks.org/wiki/ruby_programming/strings#single_quotes

当我需要多次使用正则表达式的相同长部分时,这对我很有帮助。 不是普遍的,但是我相信符合问题的例子。