Is it possible to create a dynamic regular express

2020-06-30 05:25发布

问题:

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.

回答1:

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/ 


回答2:

I fully support Isaac's solution, but you can also:

a = "\/static\/workout\/[A-Z]{1,4}" + "033112" + "[A-Z]{1,5}-EQB.html"
regex = Regexp.new(a)
stringtomatch =~ regex


标签: ruby regex