2

如何提取字符串中两个字符之间的子链接?

例如,我想在 youtube URL 中提取视频 ID:

http://www.youtube.com/watch?v=UkzbRkPv4T4&feature=g-all-u

我想要“ =”和第一个“ &”符号之间的文本,即“ UkzbRkPv4T4”。

4

4 回答 4

5

如果您不想处理正则表达式,则可以依赖 Ruby 标准库中的功能来解析 URL:

url = "http://www.youtube.com/watch?v=UkzbRkPv4T4&feature=g-all-u"
video_id = CGI.parse(URI.parse(url).query)['v'][0]
于 2012-09-26T23:31:51.153 回答
0

你只需要一个正则表达式:

uri = 'http://www.youtube.com/watch?v=UkzbRkPv4T4&feature=g-all-u'
m = uri.match /v=(?<id>\w+)&/
if m
  puts m[:id]
end
于 2012-09-26T23:23:07.010 回答
0

只是为了扩展 apneadiving 的评论。

>> url = "http://www.youtube.com/watch?v=UkzbRkPv4T4&feature=g-all-u"
=> "http://www.youtube.com/watch?v=UkzbRkPv4T4&feature=g-all-u"
>> md = url.match(/v=(.*)&/)
=> #<MatchData "v=UkzbRkPv4T4&" 1:"UkzbRkPv4T4">
>> md[1]
=> "UkzbRkPv4T4"
于 2012-09-26T23:23:50.323 回答
0
require 'uri'

uri = URI("http://www.youtube.com/watch?v=UkzbRkPv4T4&feature=g-all-u")
uri.query
# => "v=UkzbRkPv4T4&feature=g-all-u"
URI.decode_www_form(uri.query)
# => [["v", "UkzbRkPv4T4"], ["feature", "g-all-u"]]
URI.decode_www_form(uri.query).map(&:last)
# => ["UkzbRkPv4T4", "g-all-u"]
URI.decode_www_form(uri.query).assoc("v").last
# => "UkzbRkPv4T4"
于 2013-08-10T11:34:56.410 回答