根据模式在ruby中选择文本blob中的单词

时间:2012-02-03 09:36:19

标签: ruby regex nokogiri

我有一个文本blob,我想根据它们是否有.png或.jpg来选择URL。我想根据模式选择整个单词。

例如在这个blob中:

width='17'></a>&nbsp;<a href='http://click.e.groupon.com/?  qs=94bee0ddf93da5b3903921bfbe17116f859915d3a978c042430abbcd51be55d8df40eceba3b1c44e'     style=\"text-decoration: none;\">\n<img alt='Facebook' border='0' height='18'   src='http://s3.grouponcdn.com/email/images/gw-email/facebook.jpg' style='display: i

我想选择图片:

http://s3.grouponcdn.com/email/images/gw-email/facebook.jpg

我可以在html文本blob上使用nokogiri吗?

3 个答案:

答案 0 :(得分:4)

使用Nokogiri和XPath:

frag = Nokogiri::HTML.fragment(str) # Don't construct an entire HTML document
images = frag.xpath('.//img/@src').map(&:text).grep /\.(png|jpg|jpeg)\z/

XPath说:

  • .// - 此片段中的任何位置
  • img - 找到所有<img>个元素
    • /@src - 现在找到每个
    • src属性

然后我们:

  • map(&:text) - 将所有Nokogiri::XML::Attr转换为属性的值。
  • grep - 只查找数组中以相应文本结尾的字符串。

答案 1 :(得分:2)

是的,你可以使用nokogiri,你应该!

这是一个简单的片段:

require "nokogiri"
str = "....your blob"
html_doc = Nokogiri::HTML(str)
html_doc.css("a").collect{|e| e.attributes["href"].value}.select{|e| e.index(".png") || e.index(".jpeg") }

答案 2 :(得分:-1)

如果你只想找到以.jpg或.png结尾的网址,那么这样的模式就应该这样做。

https?:\/\/.*?\.(?:jpg|png)