在ruby 1.9中是否有一种方法可以从字符串中删除无效的字节序列?
假设你有一个像"€foo\xA0"
这样的字符串,编码为UTF-8,有没有办法从这个字符串中删除无效的字节序列? (所以你得到"€foo"
)
在ruby-1.8中你可以使用Iconv.iconv('UTF-8//IGNORE', 'UTF-8', "€foo\xA0")
但现在已弃用。 "€foo\xA0".encode('UTF-8')
没有做任何事情,因为它已经是UTF-8了。 我试过了:
"€foo\xA0".force_encoding('BINARY').encode('UTF-8', :undef => :replace, :replace => '')
产量
"foo"
但这也失去了有效的多字节字符€
"€foo\xA0".chars.select(&:valid_encoding?).join
"€foo\xA0".encode('UTF-16le', invalid: :replace, replace: '').encode('UTF-8')
Ruby 2.0和1.9.3
"€foo\xA0".encode(Encoding::UTF_8, Encoding::UTF_8, :invalid => :replace)
Ruby 2.1+
"€foo\xA0".scrub
data = '' if not (data.force_encoding("UTF-8").valid_encoding?)