views:

88

answers:

3

Hi!

I'm trying to store regexes in a database but they're not working when used in a .sub(), even though the same regex works when used directly in .sub() as a string.

regex = Class.object.field  // Class.object is an active record containing "\w*\s\/\s"
mystring = "first / second"

mystring.sub(/#{regex}/, '')
// => nil

mystring.sub(/\w*\s\/\s/, '') 
// => second

Any insight appreciated!

Thanks, Matt.

Editing to correct class/object terminology (thanks) & correcting my 2nd example as I had shown #{} wrapped around the working regex (cut & paste SNAFU).

+1  A: 

A String is not a Regexp. You have to create a Regexp object first.

regex = Regexp.new("\w*\s\/\s")
AboutRuby
No, you don't: `/#{some_string}/`will create a regexp using the given string. In fact `/something/` is the same as `Regexp.new("something")`.
averell
Hmm.. I completely missed that in his code. I guess I'm off on this one.
AboutRuby
+1  A: 

To answer your question: It is not quite what kind of thing your Class.object is. If it's an ActiveRecord, it won't work.

Edit: You obviously found that the problem is Rails escaping the regexp.

An ActiveRecord cannot "contain" your regular expression directly; the regexp will be in one of the fields of your record. In which case you'd want to do something like regexp = Class.object.field_containing_the_regexp.

Even if that is not the case, I suspect that the problem is that your regexp is something other than a string. You can quickly test this by using

puts "My regexp: #{regexp}"

The string that you will see in the output will be the one that is used for the regexp.

averell
"Edit: You obviously found that the problem is Rails escaping the regexp."Thanks, but it was the opposite - I found out that rails console escapes the output, and so that wasn't the problem even though it appeared to be, hence this post. Anyway, I've solved it now, thanks.
MattB
A: 

Turns out my regexp didn't cater for all cases - \w didn't account for symbols. After checking in rails console, and seeing the screwey escaping I was alreasdy half-way down the wrong track.

Thanks for the help.

MattB