ruby 1.9 有没有办法从字符串中删除无效的字节序列? [英] Is there a way in ruby 1.9 to remove invalid byte sequences from strings?
本文介绍了ruby 1.9 有没有办法从字符串中删除无效的字节序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设你有一个像 "€fooxA0"
这样的字符串,编码为 UTF-8,有没有办法从这个字符串中删除无效的字节序列?(所以你得到 "€foo"
)
Suppose you have a string like "€fooxA0"
, encoded UTF-8, Is there a way to remove invalid byte sequences from this string? ( so you get "€foo"
)
在 ruby-1.8 中,您可以使用 Iconv.iconv('UTF-8//IGNORE', 'UTF-8', "€fooxA0")
但现在已弃用."€fooxA0".encode('UTF-8')
什么都不做,因为它已经是 UTF-8.我试过了:
In ruby-1.8 you could use Iconv.iconv('UTF-8//IGNORE', 'UTF-8', "€fooxA0")
but that is now deprecated. "€fooxA0".encode('UTF-8')
doesn't do anything, since it is already UTF-8. I tried:
"€fooxA0".force_encoding('BINARY').encode('UTF-8', :undef => :replace, :replace => '')
产生
"foo"
但这也失去了有效的多字节字符€
But that also loses the valid multibyte character €
推荐答案
"€fooxA0".chars.select(&:valid_encoding?).join
这篇关于ruby 1.9 有没有办法从字符串中删除无效的字节序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文