I have these variables:
keywords = ["/(?=.*?\bTest1\b).*/i","/(?=.*?\bTest2\b)(?=.*?\bTest3\b).*(?m)^(?!.*?NotThis4)(?m)^(?!.*?NotThis5).*$/i"]
hash = {"Test2 Test3 irrelevant1"=>"Mon, 16 Feb 2015 09:26:02 +0000", "Test2 Test3 NotThis4 irrelevant2"=>"Mon, 16 Feb 2015 09:24:01 +0000", "Test1 irrelevant3 irrelevant4"=>"Mon, 16 Feb 2015 09:23:02 +0000"}
I need to run:
keywords.each do |regex|
hash.select{ |k,_| k[regex]}
end
I'm trying to collect the hashes with the keys of "Test2 Test3 irrelevant1"
and "Test1 irrelevant4 irrelevant5"
in this example. The regular expressions are not my concern, though. It is using the regular expression as/in a variable that I cannot get my head around. I tried escaping the \b
into \\b
, to no avail.
When I set a variable to a regular expression, such as:
regex = "/(?=.*?\bTest2\b)(?=.*?\bTest3\b).*(?m)^(?!.*?NotThis4)(?m)^(?!.*?NotThis5).*$/i"
The code:
hash.select{ |k,_| k[regex]}
does not work.
But if I replace the variable with the actual, literal expression:
hash.select{ |k, _| k[/(?=.*?\bTest2\b)(?=.*?\bTest3\b).*(?m)^(?!.*?NotThis4)(?m)^(?!.*?NotThis5).*$/i]}
it works just fine.
Also, the functionality works just fine with a literal string variable too:
regex = "Test1"
hash.select{ |k, _| k[regex]}
and with the literal string itself:
hash.select{ |k, _| k["Test1"]}
How do I use regular expressions in a variable, with the functionality at the top? Here again, for good measure:
keywords.each do |regex|
hash.select{ |k,_| k[regex]}
end
The regex is received as a string:
keywords.map! do |array_lineitem|
builder = ""
last = ""
array_lineitem.each do |string_element|
if string_element[0] == "-"
string_element.sub!(/^-/, '')
last += "(?m)^(?!.*?" + string_element + ")"
else
builder += "(?=.*?\b" + string_element + "\b)"
end
end
if last.empty?
throwback = "/" + builder + ".*/i"
else
throwback = "/" + builder + ".*" + last + ".*$" + "/i"
end
end
Converting the string to regexp, I tried the to_regexp gem, the Regexp.escape, Regexp.union and eval(string), but again with no luck. The \b
gets converted to \x08
with each of these methods.