代码之家  ›  专栏  ›  技术社区  ›  dpigera

Ruby Hpricot RegEx将<BR>替换为<P>

  •  2
  • dpigera  · 技术社区  · 16 年前

    有人能告诉我如何使用Hpricot&正则表达式?

    // Replace all doubled-up <BR> tags with <P> tags, and remove fonts.
        var pattern =  new RegExp ("<br/?>[ \r\n\s]*<br/?>", "g");
        document.body.innerHTML = document.body.innerHTML.replace(pattern, "</p><p>").replace(/<\/?font[^>]*>/g, '');
    

    我设置的代码是:

    require 'rubygems'
    require 'hpricot'
    require 'open-uri'
    
    @file = Hpricot(open("http://www.bubl3r.com/article.html"))
    

    谢谢

    3 回复  |  直到 16 年前
        1
  •  1
  •   Andrew Grimm Alex Wayne    15 年前

    OPs URL的内容似乎已经发生了变化,这在互联网上很常见,所以我拼凑了一些示例HTML来展示我将如何做。

    而且 Nokogiri 是我推荐的Ruby HTML/XML解析器,因为它非常受支持、健壮且灵活。

    require 'nokogiri'
    
    html = <<EOT
    <html>
    <body>
      some<br><br>text
      <font>
        text wrapped with font
      </font>
      some<br>more<br>text
    </body>
    </html>
    EOT
    
    doc = Nokogiri::HTML(html)
    
    # Replace all doubled-up <BR> tags with <P> tags, and remove fonts.
    doc.search('br').each do |n|
      if (n.previous.name == 'br')
        n.previous.remove 
        n.replace('<p>')
      end
    end
    
    doc.search('font').each do |n|
      n.replace(n.content)
    end
    
    print doc.to_html
    # >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    # >> <html><body>
    # >>   some<p></p>text
    # >>   
    # >>     text wrapped with font
    # >>   
    # >>   some<br>more<br>text
    # >> </body></html>
    
        2
  •  0
  •   VGE    15 年前

    我认为清理html文件的更好方法是漂亮的汤。我在python中使用它,它做得很好,因为它模拟了html浏览器的部分语义。

    http://www.crummy.com/software/RubyfulSoup/

        3
  •  0
  •   TuteC    15 年前

    尽管它不会生成有效的HTML,但像这样的方法仍然有效:

    require 'rubygems'
    require 'hpricot'
    require 'open-uri'
    
    @file = Hpricot(open("http://www.bubl3r.com/article.html"))
    puts @file.html.gsub('<br />', '<p>')