# String.match on variable holding a regex?

**URL:** <https://www.ruby-forum.com/t/string-match-on-variable-holding-a-regex/112840>\
**Category:** Ruby\
**Created:** [August 23, 2007, 7:23pm UTC](https://www.ruby-forum.com/t/string-match-on-variable-holding-a-regex/112840 "2007-08-23T19:23:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![upenox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/c2a13f/32.png) [@upenox](https://www.ruby-forum.com/u/upenox)\
**Post date:** [August 23, 2007, 7:23pm UTC](https://www.ruby-forum.com/t/string-match-on-variable-holding-a-regex/112840/1 "2007-08-23T19:23:46Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![upenox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/c2a13f/32.png) [@upenox](https://www.ruby-forum.com/u/upenox)\
**Post date:** [August 23, 2007, 7:37pm UTC](https://www.ruby-forum.com/t/string-match-on-variable-holding-a-regex/112840/2 "2007-08-23T19:37:21Z")

</div>

Hi –

On Fri, 24 Aug 2007, Finn K. wrote:

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

---

<div class="post-metadata">

**Author:** ![upenox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/c2a13f/32.png) [@upenox](https://www.ruby-forum.com/u/upenox)\
**Post date:** [August 23, 2007, 8:02pm UTC](https://www.ruby-forum.com/t/string-match-on-variable-holding-a-regex/112840/3 "2007-08-23T20:02:54Z")

</div>

David A. Black wrote:

> David

Wow, that was dumb…I forgot about using interpolation(sp?) on there.  
Thanks!!! 😃
