8

我想使用带有字符串的 grep 作为正则表达式模式。我怎样才能做到这一点?

例子:

myArray.grep(/asd/i) #Works perfectly.

但我想先准备我的陈述

searchString = '/asd/i'
myArray.grep(searchString) # Fails

我怎样才能做到这一点?我需要准备一个字符串,因为这将进入搜索算法,并且查询会根据每个请求而改变。谢谢。

4

5 回答 5

12

正则表达式支持插值,就像字符串一样:

var = "hello"
re = /#{var}/i
p re #=> /hello/i
于 2012-05-10T13:17:55.200 回答
4

引号中的内容与事物本身不同。/a/i是正则表达式,"/a/i"是字符串。要从字符串构造正则表达式,请执行以下操作:

r = Regexp.new str
myArray.grep(r)
于 2012-05-10T12:18:02.587 回答
1

尝试这个:

searchString = /asd/i
myArray.grep(searchString)
于 2012-05-10T12:16:04.770 回答
1

编辑:

我找到了更好的方法

myString = "Hello World!"
puts "Hello World!"
puts "Enter word to search"
input_search = gets.chomp
puts "Search insensitive? y/n"

answer = gets.chomp

if answer == "y"
  ignore = "Regexp::IGNORECASE"
else
  ignore = false
end

puts myString.lines.grep(Regexp.new(input_search, ignore))

我的旧答案如下:

如果他们想要打开或关闭不敏感的搜索等,请尝试将其设为 case 或 if 语句传递

myString = "Hello World!"
puts "Enter word to search"
input_search = gets.chomp
puts "Search insensitive? y/n"
case gets.chomp
  when "y"
    puts myString.lines.grep(Regexp.new(/#{input_search}/i))
  when "n"
    puts myString.lines.grep(Regexp.new(/#{input_search}/))
end
于 2016-08-07T18:02:14.507 回答
0

'/asd/i' 是一个字符串。为什么不让它成为正则表达式?如果您需要从 String 转到 Regexp,一种方法是创建一个新的 Regexp 对象:

>> re = Regexp.new('/asd/i')
=> /\/asd\/i/ 
>> re = Regexp.new("asd", "i")
=> /asd/i 

所以也许,

>> str = gets.chomp #user inputs 
=> "Hello World"
re = Regexp.new(str, "i")
=> /Hello World/i

就是你要找的。

但总的来说,我认为您不能简单地“将字符串用作正则表达式模式”,尽管我是初学者并且可能对此有误。

于 2018-01-26T19:21:02.333 回答