Regex – Is it possible to create a dynamic regular expression in Ruby

regexruby

I'm using the following regular expression to march hrefs on a web page.

\/static\/workout\/[A-Z]{1,4}032812[A-Z]{1,5}-EQB.html

I'd like to find a way to make the 032812 portion of the regular expression dynamic, such that the value would reflect the current date. Fore example, on March 31, 2012 the regular expression would look like:

\/static\/workout\/[A-Z]{1,4}033112[A-Z]{1,5}-EQB.html

I tried creating a string

a = \/static\/workout\/[A-Z]{1,4}033112[A-Z]{1,5}-EQB.html

and then

\ a \

but this didn't work. Is there a way of doing this.

Best Solution

You can use #{} just like in a string.

1.9.2p290 :001 > some_string = "033112"
 => "033112" 
1.9.2p290 :002 > a_regex = /[A-Z]{1,4}#{some_string}[A-Z]{1-5}-EQB.html/
 => /[A-Z]{1,4}033112[A-Z]{1-5}-EQB.html/