本文介绍了使用变量名的 Ruby 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 ruby​​ 中创建/使用基于变量名称值的正则表达式模式?

Is is possible to create/use a regular expression pattern in ruby that is based on the value of a variable name?

例如,我们都知道我们可以使用 Ruby 字符串执行以下操作:

For instance, we all know we can do the following with Ruby strings:

str = "my string"
str2 = "This is #{str}" # => "This is my string"

我想用正则表达式做同样的事情:

I'd like to do the same thing with regular expressions:

var = "Value"
str = "a test Value"
str.gsub( /#{var}/, 'foo' ) # => "a test foo"

显然,这并不像列出的那样工作,我只是把它放在那里作为一个例子来展示我想要做什么.我需要根据变量内容的值进行正则表达式匹配.

Obviously that doesn't work as listed, I only put it there as an example to show what I'd like to do. I need to regexp match based on the value of a variable's content.

推荐答案

你认为行不通的代码,行了:

The code you think doesn't work, does:

var = "Value"
str = "a test Value"
p str.gsub( /#{var}/, 'foo' )   # => "a test foo"

如果 var 可以包含正则表达式元字符,事情会变得更有趣.如果确实如此,并且您希望这些 matacharacters 执行它们通常在正则表达式中执行的操作,那么相同的 gsub 将起作用:

Things get more interesting if var can contain regular expression meta-characters. If it does and you want those matacharacters to do what they usually do in a regular expression, then the same gsub will work:

var = "Value|a|test"
str = "a test Value"
str.gsub( /#{var}/, 'foo' ) # => "foo foo foo"

但是,如果您的搜索字符串包含元字符并且您希望它们被解释为元字符,那么使用 Regexp.escape 像这样:

However, if your search string contains metacharacters and you do not want them interpreted as metacharacters, then use Regexp.escape like this:

var = "*This*"
str = "*This* is a string"
p str.gsub( /#{Regexp.escape(var)}/, 'foo' )
# => "foo is a string"

或者只是给 gsub 一个字符串而不是一个正则表达式.在 MRI >= 1.8.7 中,gsub 会将字符串替换参数视为普通字符串,而不是正则表达式:

Or just give gsub a string instead of a regular expression. In MRI >= 1.8.7, gsub will treat a string replacement argument as a plain string, not a regular expression:

var = "*This*"
str = "*This* is a string"
p str.gsub(var, 'foo' ) # => "foo is a string"

(以前是 gsub 的字符串替换参数会自动转换为正则表达式.我知道 1.6 中是这样.我不记得是哪个版本引入了更改).

(It used to be that a string replacement argument to gsub was automatically converted to a regular expression. I know it was that way in 1.6. I don't recall which version introduced the change).

如其他答案所述,您可以使用 Regexp.new 作为插值的替代方法:

As noted in other answers, you can use Regexp.new as an alternative to interpolation:

var = "*This*"
str = "*This* is a string"
p str.gsub(Regexp.new(Regexp.escape(var)), 'foo' )
# => "foo is a string"

这篇关于使用变量名的 Ruby 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:36