将字符串插入正则表达式

Chr*_*nch 149 ruby regex

我需要将字符串的值替换为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
Run Code Online (Sandbox Code Playgroud)

Jon*_*ski 262

与字符串插入相同.

if goo =~ /#{Regexp.quote(foo)}/
#...
Run Code Online (Sandbox Code Playgroud)

  • `Regexp#quote` 是 `Regexp#escape` 的别名。https://devdocs.io/ruby~3.2/regexp#method-c-quote (2认同)

gle*_*ald 117

需要注意的是,Regexp.quote乔恩L.的回答是很重要的!

if goo =~ /#{Regexp.quote(foo)}/
Run Code Online (Sandbox Code Playgroud)

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

if goo =~ /#{foo}/
Run Code Online (Sandbox Code Playgroud)

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

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

if goo.include?(foo)
Run Code Online (Sandbox Code Playgroud)

这不需要额外的引用或担心特殊字符.

  • 请注意,如果您要使用字符串构造正则表达式,则反向(不使用`.quote()`)也很有用. (3认同)

Jas*_*rue 6

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

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


Mar*_*rot 6

Regexp.compile(Regexp.escape(foo))
Run Code Online (Sandbox Code Playgroud)