我想使用带有字符串的 grep 作为正则表达式模式。我怎样才能做到这一点?
例子:
myArray.grep(/asd/i) #Works perfectly.
但我想先准备我的陈述
searchString = '/asd/i'
myArray.grep(searchString) # Fails
我怎样才能做到这一点?我需要准备一个字符串,因为这将进入搜索算法,并且查询会根据每个请求而改变。谢谢。
正则表达式支持插值,就像字符串一样:
var = "hello"
re = /#{var}/i
p re #=> /hello/i
引号中的内容与事物本身不同。/a/i
是正则表达式,"/a/i"
是字符串。要从字符串构造正则表达式,请执行以下操作:
r = Regexp.new str
myArray.grep(r)
尝试这个:
searchString = /asd/i
myArray.grep(searchString)
编辑:
我找到了更好的方法
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
'/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
就是你要找的。
但总的来说,我认为您不能简单地“将字符串用作正则表达式模式”,尽管我是初学者并且可能对此有误。