Ruby grep with string argument

I want to use grep with a string as a regular expression pattern. How can i do this?

Example:

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

But I want to prepare my expression first

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

How can i achieve this? I need a string prepared because it goes to the search algorithm and the query will change with every query. Thanks.

+6
source share
5 answers

Regular expressions support interpolation, just like strings:

 var = "hello" re = /#{var}/i p re #=> /hello/i 
+9
source

The presence of something in quotation marks does not coincide with the thing itself. /a/i is regexp, "/a/i" is a string. To build Regexp from a string, do the following:

 r = Regexp.new str myArray.grep(r) 
+4
source

Try the following:

 searchString = /asd/i myArray.grep(searchString) 
+1
source

Edit:

I found a better way

 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)) 

My old answer is below:

Try to make it random, or if the statement is passed, if they want to enable or disable insensitive search, etc.

 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 
+1
source

'/ asd / i' is a string. Why not make Regrexp? If you need to go from String to Regexp, one way to do this is to create a new Regexp object:

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

So maybe

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

- this is what you are looking for.

But overall, I don’t think you can just β€œuse the string as a regular expression pattern,” although I am new to and probably wrong.

0
source

Source: https://habr.com/ru/post/915396/


All Articles