-1

我需要从 url 中提取后缀,意思是:

http://google.com/sports/golf => 运动/高尔夫 http://yahoo.com/blog?id=7 => blog/id=7

我怎样才能用正则表达式(红宝石风格)来实现这一点?

谢谢

4

3 回答 3

2

URI模块与.path + .query.

uri = URI("http://google.com/sports/golf")
uri.path + "/" + uri.query
于 2013-04-02T14:14:01.177 回答
1

下面怎么样:)

require 'uri'
p URI.split("http://google.com/sports/golf").compact.drop(2).join("/")
p URI.split("http://yahoo.com/blog?id=7").compact.drop(2).join("/")

或者,

require 'uri'

a = ["http://google.com/sports/golf","http://stackoverflow.com/questions/15766337/extract-suffix-from-url-regex/15766456#15766456","http://yahoo.com/blog?id=7"]
a.each { |url| p URI.split(url).compact.drop(2).join("/") }

输出:

"/sports/golf"
"/questions/15766337/extract-suffix-from-url-regex/15766456/15766456"
"/blog/id=7"
于 2013-04-02T14:17:16.470 回答
1

试试这个:

irb(main):011:0> /(?:http:\/\/\w+\.\w+\/)(.+)/.match("http://yahoo.com/blog?id=7")[1]
=> "blog?id=7"
irb(main):012:0> /(?:http:\/\/\w+\.\w+\/)(.+)/.match("http://google.com/sports/golf")[1]
=> "sports/golf"
irb(main):013:0> 
于 2013-04-02T14:25:29.333 回答