Ruby grep with string argument
14,433
Solution 1
Regular expressions support interpolation, just like strings:
var = "hello"
re = /#{var}/i
p re #=> /hello/i
Solution 2
Having something in quotes is not the same as the thing itself. /a/i
is Regexp, "/a/i"
is string. To construct a Regexp from string do this:
r = Regexp.new str
myArray.grep(r)
Solution 3
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 below:
Try making it a case or if statement passing if they want insensitive search on or off, 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
Solution 4
Try this:
searchString = /asd/i
myArray.grep(searchString)
Author by
gkaykck
Updated on June 16, 2022Comments
-
gkaykck almost 2 years
I want to use grep with a string as regex pattern. How can i do that?
Example:
myArray.grep(/asd/i) #Works perfectly.
But i want to prepare my statement first
searchString = '/asd/i' myArray.grep(searchString) # Fails
How can i achieve this? I need a string prepared because this is going into a search algorithm and query is going to change on every request. Thanks.
-
gkaykck about 12 yearsi can't,i have a string comes from a user, how can i merge that string with /asd/i ?
-
gkaykck about 12 yearsRegexp.new('/asd/i') returns a regex like (?-mix:\/asd\/i)?
-
Ivaylo Strandjev about 12 years@gkaykck the result is not the same on my machine, still what I wanted to stress on is that a regexp is not a string. I am simply showing you how to construct a regexp from a string. In the example above if str = "/u/" then r will become /\/u\// which is not what you want, I believe you can figure out how to do what you want
-
Matstar almost 8 yearsNote that you may want to escape the value before you interpolate it, especially if it's provided by an untrusted user:
/#{Regexp.escape(user_provided_string)}/i
orRegexp.new(Regexp.escape(user_provided_string), "i")
. This would for example treat a "." as a literal "." character and not as "any character". As a short but cryptic way to both escape a string and turn it into a regex, you can doRegexp.union(user_provided_string)
.