是否可以在 Ruby 中创建动态正则表达式 [英] Is it possible to create a dynamic regular expression in Ruby

查看:42
本文介绍了是否可以在 Ruby 中创建动态正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下正则表达式在网页上显示 hrefs.

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

我想找到一种方法来使正则表达式的 032812 部分动态化,以便该值反映当前日期.例如,2012 年 3 月 31 日的正则表达式如下所示:

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

我尝试创建一个字符串

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

然后

\ a \

但这没有用.有没有办法做到这一点.

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

推荐答案

您可以像在字符串中一样使用 #{}.

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/ 

这篇关于是否可以在 Ruby 中创建动态正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆