将字符串插入正则表达式

时间:2020-03-06 14:53:25  来源:igfitidea点击:

我需要将字符串的值替换为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

解决方案

使用Regexp.new:

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

Regexp.escape(foo)可能是一个起点,但是有充分的理由不能使用更传统的表达式插值方法:"我的东西#{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}/

请注意,乔恩·L(Jon L.)回答中的Regexp.quote很重要!

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

如果我们只是执行"显而易见的"版本:

if goo =~ /#{foo}/

则匹配文本中的句点将被视为正则表达式通配符," 0.0.0.0"将匹配" 0a0b0c0"。

另请注意,如果我们确实只想检查子字符串是否匹配,则只需执行以下操作

if goo.include?(foo)

不需要额外的引号或者担心特殊字符。