有人可以告诉我如何使用 Hpricot 和 RegEx 将这行 Javascript 转换为 Ruby 吗?
// 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"))
谢谢
最佳答案
OP 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>
关于javascript - Ruby Hpricot RegEx 替换 <BR >'s with <P>' s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3436725/