如何从文本中提取URL

时间:2010-09-08 06:17:01

标签: ruby

如何从Ruby中的纯文本文件中提取所有URL?

我尝试了一些库,但在某些情况下它们失败了。什么是最好的方式?

6 个答案:

答案 0 :(得分:89)

如果您喜欢使用Ruby中已经提供的内容:

require "uri"
URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
# => ["http://foo.example.org/bla", "mailto:test@example.com"]

了解详情:http://railsapi.com/doc/ruby-v1.8/classes/URI.html#M004495

答案 1 :(得分:11)

我使用了twitter-text gem

require "twitter-text"
class UrlParser
    include Twitter::Extractor
end

urls = UrlParser.new.extract_urls("http://stackoverflow.com")
puts urls.inspect

答案 2 :(得分:8)

您可以使用正则表达式和.scan()

string.scan(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/)

您可以开始使用该正则表达式并根据您的需要进行调整。

答案 3 :(得分:4)

哪些案例失败了?

根据图书馆regexpert,您可以使用

regexp = /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix

然后对文字执行scan

编辑:似乎正则表达式支持空字符串。只需删除最初的(^$),即可完成

答案 4 :(得分:0)

如果您的输入与此类似:

"http://i.imgur.com/c31IkbM.gifv;http://i.imgur.com/c31IkbM.gifvhttp://i.imgur.com/c31IkbM.gifv"

即。 URL不一定在它们周围有空格,可以用任何分隔符分隔,或者它们之间没有分隔符,你可以使用以下方法:

def process_images(raw_input)
  return [] if raw_input.nil?
  urls = raw_input.split('http')
  urls.shift
  urls.map { |url| "http#{url}".strip.split(/[\s\,\;]/)[0] }
end

希望它有所帮助!

答案 5 :(得分:-2)

require 'uri'    
foo = #<URI::HTTP:0x007f91c76ebad0 URL:http://foobar/00u0u_gKHnmtWe0Jk_600x450.jpg>
foo.to_s
=> "http://foobar/00u0u_gKHnmtWe0Jk_600x450.jpg"

编辑:解释

对于那些通过JSON响应解析URI或使用像Nokogiri或Mechanize这样的抓取工具出现问题的人来说,这个解决方案对我有用。