开发者

regex to remove the webpage part of a url in ruby

开发者 https://www.devze.com 2023-01-18 00:30 出处:网络
I am trying to remove the webpage part of the URL For example, www.example.com/home/index.html to www.ex开发者_运维问答ample.com/home

I am trying to remove the webpage part of the URL

For example,

www.example.com/home/index.html 

to

www.ex开发者_运维问答ample.com/home 

any help appreciated.

Thanks


It's probably a good idea not to use regular expressions when possible. You may summon Cthulhu. Try using the URI library that's part of the standard library instead.

require "uri"
result = URI.parse("http://www.example.com/home/index.html")
result.host # => www.example.com
result.path # => "/home/index.html"
# The following line is rather unorthodox - is there a better solution?
File.dirname(result.path) # => "/home"
result.host + File.dirname(result.path) # => "www.example.com/home"


If your heart is set on using regex and you know that your URLs will be pretty straight forward you could use (.*)/.* to capture everything before the last / in your URL.

irb(main):007:0> url = "www.example.com/home/index.html"
=> "www.example.com/home/index.html"
irb(main):008:0> regex = "(.*)/.*"
=> "(.*)/.*"
irb(main):009:0> url =~ /#{regex}/
=> 0
irb(main):010:0> $1
=> "www.example.com/home"


irb(main):001:0> url="www.example.com/home/index.html"
=> "www.example.com/home/index.html"
irb(main):002:0> url.split("/")[0..-2].join("/")
=> "www.example.com/home"
0

精彩评论

暂无评论...
验证码 换一张
取 消