如何从字符串中提取包含非英语字符的URL?

bio*_*iel 9 ruby string url uri ruby-on-rails

这是一个简单的脚本,它带有一个带有德语URL的锚标记,并提取URL:

# encoding: utf-8

require 'uri'

url = URI.extract('<a href="http://www.example.com/wp content/uploads/2012/01/München.jpg">München</a>')

puts url
Run Code Online (Sandbox Code Playgroud)
http://www.example.com/wp-content/uploads/2012/01/M
Run Code Online (Sandbox Code Playgroud)

extract方法停在ü.如何才能使用非英文字母?我正在使用ruby-1.9.3-p0.

the*_*Man 12

Ruby的内置URI对某些东西很有用,但在处理国际字符或IDNA地址时它不是最佳选择.为此,我建议使用Addressable gem.

这是一些清理过的IRB输出:

require 'addressable/uri'
url = 'http://www.example.com/wp content/uploads/2012/01/München.jpg'
uri = Addressable::URI.parse(url)
Run Code Online (Sandbox Code Playgroud)

这就是Ruby现在所知道的:

#<Addressable::URI:0x102c1ca20
    @uri_string = nil,
    @validation_deferred = false,
    attr_accessor :authority = nil,
    attr_accessor :host = "www.example.com",
    attr_accessor :path = "/wp content/uploads/2012/01/München.jpg",
    attr_accessor :scheme = "http",
    attr_reader :hash = nil,
    attr_reader :normalized_host = nil,
    attr_reader :normalized_path = nil,
    attr_reader :normalized_scheme = nil
>
Run Code Online (Sandbox Code Playgroud)

看着路径,你可以看到它,或者它应该是:

1.9.2-p290 :004 > uri.path            # => "/wp content/uploads/2012/01/München.jpg"
1.9.2-p290 :005 > uri.normalized_path # => "/wp%20content/uploads/2012/01/M%C3%BCnchen.jpg"
Run Code Online (Sandbox Code Playgroud)

考虑到互联网如何转向更复杂的URI和混合的Unicode字符,应该选择Addressable来替换Ruby的URI.

现在,获取字符串也很容易,但取决于您需要查看多少文本.

如果您有完整的HTML文档,最好的办法是使用Nokogiri解析HTML并href<a>标记中提取参数.这是一个单一的开始<a>:

require 'nokogiri'
html = '<a href="http://www.example.com/wp content/uploads/2012/01/München.jpg">München</a>'
doc = Nokogiri::HTML::DocumentFragment.parse(html)

doc.at('a')['href'] # => "http://www.example.com/wp content/uploads/2012/01/München.jpg"
Run Code Online (Sandbox Code Playgroud)

解析使用DocumentFragment避免将片段包装在通常的<html><body>标签中.对于您想要使用的完整文档:

doc = Nokogiri::HTML.parse(html)
Run Code Online (Sandbox Code Playgroud)

这是两者之间的区别:

irb(main):006:0> Nokogiri::HTML::DocumentFragment.parse(html).to_html
=> "<a href=\"http://www.example.com/wp%20content/uploads/2012/01/M%C3%BCnchen.jpg\">München</a>"
Run Code Online (Sandbox Code Playgroud)

与:

irb(main):007:0> Nokogiri::HTML.parse(html).to_html
=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><a href=\"http://www.example.com/wp%20content/uploads/2012/01/M%C3%BCnchen.jpg\">München</a></body></html>\n"
Run Code Online (Sandbox Code Playgroud)

因此,使用第二个用于完整的HTML文档,对于一个小的部分块,使用第一个.

要扫描整个文档,提取所有href,请使用:

hrefs = doc.search('a').map{ |a| a['href'] }
Run Code Online (Sandbox Code Playgroud)

如果你只有你在示例中显示的小字符串,你可以考虑使用一个简单的正则表达式来隔离所需的href:

html[/href="([^"]+)"/, 1]
=> "http://www.example.com/wp content/uploads/2012/01/München.jpg"
Run Code Online (Sandbox Code Playgroud)