如何删除4字节utf-8字符在Ruby? [英] How to remove 4 byte utf-8 characters in Ruby?

查看:232
本文介绍了如何删除4字节utf-8字符在Ruby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于MySQL的utf8不支持4字节字符,我正在寻找一种方法来检测和消除Ruby中的字符串中的任何4字节utf8字符。我理解我可以更新我的表使用utf8m4,但由于几个原因是不可能的或所需的解决方案。

Since MySQL's utf8 doesn't support 4 byte characters, I'm looking for a way to detect and eliminate any 4 byte utf8 characters from a string in Ruby. I understand that I can update my table to use utf8m4 but for a couple reasons that's not possible or the desired solution.

只需将字符串编码为ASCII将删除这些字符,

Simply encoding the string to ASCII will remove these characters but will also remove all other non-ASCII characters, which is not good.

推荐答案

以下似乎在Ruby 1.9中适用于我.3:

The following seems to work for me in Ruby 1.9.3:

input.each_char.select{|c| c.bytes.count < 4 }.join('')

例如:

input = "hello \xF0\xA9\xB6\x98 world"                  # includes U+29D98
input.each_char.select{|c| c.bytes.count < 4 }.join('') # 'hello  world'

这篇关于如何删除4字节utf-8字符在Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆