【发布时间】:2016-01-19 14:48:38
【问题描述】:
我有这个链接,我声明如下:
link = "<a href=\"https://www.congress.gov/bill/93rd-congress/house-bill/11461\">H.R.11461</a>"
问题是如何使用正则表达式仅提取 href 值?
谢谢!
【问题讨论】:
标签: ruby regex html-parsing
我有这个链接,我声明如下:
link = "<a href=\"https://www.congress.gov/bill/93rd-congress/house-bill/11461\">H.R.11461</a>"
问题是如何使用正则表达式仅提取 href 值?
谢谢!
【问题讨论】:
标签: ruby regex html-parsing
如果要解析 HTML,可以使用 Nokogiri gem 而不是使用正则表达式。这要容易得多。
例子:
require "nokogiri"
link = "<a href=\"https://www.congress.gov/bill/93rd-congress/house-bill/11461\">H.R.11461</a>"
link_data = Nokogiri::HTML(link)
href_value = link_data.at_css("a")[:href]
puts href_value # => https://www.congress.gov/bill/93rd-congress/house-bill/11461
【讨论】:
【讨论】:
您应该能够使用这样的正则表达式:
href\s*=\s*"([^"]*)"
查看该表达式的this Rubular example。
捕获组将为您提供 URL,例如:
link = "<a href=\"https://www.congress.gov/bill/93rd-congress/house-bill/11461\">H.R.11461</a>"
match = /href\s*=\s*"([^"]*)"/.match(link)
if match
url = match[1]
end
href 匹配 href 属性\s* 匹配 0 个或多个空白字符(这是可选的 - 只有当 HTML 可能不是规范形式时才需要它)。= 匹配等号\s* 再次允许可选空格" 匹配 href URL 的开头引号( 开始一个捕获组,用于提取其中匹配的任何内容[^"]* 匹配 0 个或多个非引号字符。由于必须对 HTML 属性中的引号进行转义,这将匹配到 URL 末尾的所有字符。) 结束捕获组" 匹配 href 属性值的右引号【讨论】: