如何使用ruby regex从标签中提取href?

Ryz*_*off 2 ruby regex html-parsing

我有这个链接,我声明如下:

link = "<a href=\"https://www.congress.gov/bill/93rd-congress/house-bill/11461\">H.R.11461</a>"
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

小智 6

如果要解析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
Run Code Online (Sandbox Code Playgroud)


neu*_*aut 5

您应该能够使用这样的正则表达式:

href\s*=\s*"([^"]*)"
Run Code Online (Sandbox Code Playgroud)

请参阅表达式的Rubular示例.

捕获组将为您提供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
Run Code Online (Sandbox Code Playgroud)

表达式的解释:

  • href 匹配href属性
  • \s* 匹配0个或更多的空格字符(这是可选的 - 如果HTML可能不是规范形式,则只需要它).
  • = 匹配等号
  • \s* 再次允许可选的空格
  • " 匹配href URL的开头引用
  • ( 开始一个捕获组,用于提取其中匹配的内容
  • [^"]*匹配0个或更多非引号字符.由于必须对HTML属性中的引号进行转义,因此这将匹配所有字符,直到URL的末尾.
  • ) 结束捕获组
  • " 匹配href属性值的结束引用