4 回答

TA貢獻1843條經驗 獲得超7個贊
我建議您使用HTML解析器。只要找到最快的一個。
解析HTML并不像看起來那樣容易。
瀏覽器會在UTF-8 HTML文檔中解析無效的UTF-8序列,只需將“ ...”符號放入即可。因此,一旦解析了HTML中的無效UTF-8序列,生成的文本便是有效字符串。
即使在屬性值內部,您也必須解碼amp等HTML實體
這是一個很好的問題,總結了為什么不能可靠地使用正則表達式解析HTML: RegEx匹配除XHTML自包含標簽之外的其他打開標簽

TA貢獻1817條經驗 獲得超6個贊
attachment = file.read
begin
# Try it as UTF-8 directly
cleaned = attachment.dup.force_encoding('UTF-8')
unless cleaned.valid_encoding?
# Some of it might be old Windows code page
cleaned = attachment.encode( 'UTF-8', 'Windows-1252' )
end
attachment = cleaned
rescue EncodingError
# Force it to UTF-8, throwing out invalid bits
attachment = attachment.force_encoding("ISO-8859-1").encode("utf-8", replace: nil)
end
- 4 回答
- 0 關注
- 717 瀏覽
添加回答
舉報