String.match on variable holding a regex?

F

Finn Koch

Hi, I'm having a little problem with matching a regex against a string.
I am storing data in mysql as a regex. At some point I need to match a
string to this regex. Here is what I am working with:


result = @dbconn.query("SELECT id, to_user_regex FROM next")
result.each do |row|
@to_user_regex = row[1]
@messages << row[0] if
@user.match(/@to_user_regex/)
end


So lets say @user is a string holding 'name1' and @to_user_regex is
'name1|name2'. I'm trying to match this. Does anyone have any ideas as
to why this wouldn't be matching?

Thanks!

upenox
 
D

David A. Black

Hi --

Hi, I'm having a little problem with matching a regex against a string.
I am storing data in mysql as a regex. At some point I need to match a
string to this regex. Here is what I am working with:


result = @dbconn.query("SELECT id, to_user_regex FROM next")
result.each do |row|
@to_user_regex = row[1]
@messages << row[0] if
@user.match(/@to_user_regex/)
end


So lets say @user is a string holding 'name1' and @to_user_regex is
'name1|name2'. I'm trying to match this. Does anyone have any ideas as
to why this wouldn't be matching?

If you do /@x/, you're matching the pattern "@x". If you want to use
the string as a regex, you would do either:

/#{@x}/.match(string)

or

Regexp.new(@x).match(string)

In your example, you'd want:

/#{@to_user_regex}/.match(@user)

assuming @user is a string. You might have to tweak this for your
particular case, but that should get you started.


David

--
* Books:
RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
& consulting: Ruby Power and Light, LLC (http://www.rubypal.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top