如何在 Ruby 字符串中返回最后一个斜杠(/)之后的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11081504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you return everything after last slash(/) in a Ruby string
提问by Hendrik
I have a string would like everything after the last /to be returned.
我有一个字符串希望/返回最后一个之后的所有内容。
E.g. for https://www.example.org/hackerbob, it should return "hackerbob".
例如https://www.example.org/hackerbob,它应该返回"hackerbob"。
回答by Niklas B.
I don't think a regex is a good idea, seeing how simple the task is:
我不认为正则表达式是一个好主意,看看任务是多么简单:
irb(main):001:0> s = 'https://www.facebook.com/hackerbob'
=> "https://www.facebook.com/hackerbob"
irb(main):002:0> s.split('/')[-1]
=> "hackerbob"
Of course you could also do it using regex, but it's a lot less readable:
当然,你也可以使用正则表达式来完成,但它的可读性要差得多:
irb(main):003:0> s[/([^\/]+)$/]
=> "hackerbob"
回答by Lars Haugseth
Use the right tool for the job:
为工作使用正确的工具:
require 'uri'
url = "https://www.facebook.com/hackerbob"
URI.parse(url).path[1..-1] # => "hackerbob"
回答by Ribtoks
One more sample
再来一份样品
str = 'https://www.facebook.com/hackerbob'
ending = str.match(/.com\/(.*)/)
p ending[1]
回答by NahAbiah
You can try /[a-zA-Z]+://[a-z]+.[a-z]+.[a-z]+/(.+)/ if you are using it for the string above or any other similar url. A great tool to use for regex is http://www.rubular.com
您可以尝试 /[a-zA-Z]+://[az]+.[az]+.[az]+/(.+)/ 如果您将它用于上面的字符串或任何其他类似的网址。用于正则表达式的一个很好的工具是http://www.rubular.com
回答by Andrea Salicetti
Sure you can:
你当然可以:
string = 'https://www.facebook.com/hackerbob'
string =~ /^https?:\/\/www\.facebook\.com\/(.*)/
回答by Cylian
May use this
可以用这个
subject = /(\/)([^\/]+)\Z/i.match(subject)
if match
# match start: match.begin(0)
# match end (exclusive): match.end(0)
# matched text: match[0]
# backreference n start: match.begin(n)
# backreference n end (exclusive): match.end(n)
# backreference n text: match[n]
else
# Match attempt failed
end
回答by Shamith c
Use It
用它
1.9.3p194 :039 > line = 'https://www.facebook.com/hackerbob'
1.9.3p194 :039 > line.match(/.com\/(\w+$)/)[1] # => "hackerbob"

