获取指定字符串之间的数字

时间:2009-04-16 22:50:26

标签: ruby-on-rails ruby regex

确定。举个例子:

http://example.com/news/3226-some-post-title.html

我正试图获得3226.这个正则表达式:http://interaktywnie.com/newsy/(.*)。 似乎不起作用。请帮忙。

感谢。

4 个答案:

答案 0 :(得分:2)

你可以使用:

   /\/(\d+)-(.*)\.html$/

这将获取'/'后的数字(\ d),并在找到数字后将数字放入第一个变量。

测试正则表达式的好地方是http://rubular.com/

答案 1 :(得分:1)

你想要这个:

/http:\/\/example.com\/news\/(\d+)-.+\.html/

\ d是任何数字。此外,以下站点对ruby中的正则表达式非常有用:

http://www.rubular.com

答案 2 :(得分:1)

"http://example.com/news/3226-some-post-title.html".split("/").last.to_i

答案 3 :(得分:0)

尝试这种模式:

/http:\/\/example\.com\/news\/(\d+)-.+\.html/

所以:

match = /http:\/\/example\.com\/news\/(\d+)-.+\.html/.match("http://example.com/news/3226-some-post-title.html")
puts match[1]