如何使用 ruby 正则表达式从标签中提取 href?

How to extract href from a tag using ruby regex?

我有这个link,我是这样声明的:

link = "<a href=\"https://www.congress.gov/bill/93rd-congress/house-bill/11461\">H.R.11461</a>"

问题是如何使用正则表达式只提取 href 值?

谢谢!

您应该可以像这样使用正则表达式:

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 属性值的右引号

为了仅捕获 url,您可以这样做:

/(href\s*\=\s*\\")(.*)(?=\)/

并使用第二个匹配项。

http://rubular.com/r/qcqyPv3Ww3

如果要解析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