How to remove 4 byte utf-8 characters in Ruby?

2019-03-12 21:37发布

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.

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

1条回答
Melony?
2楼-- · 2019-03-12 22:12

The following seems to work for me in Ruby 1.9.3:

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

For example:

input = "hello \xF0\xA9\xB6\x98 world"                  # includes U+29D98
input.each_char.select{|c| c.bytes.count < 4 }.join('') # 'hello  world'
查看更多
登录 后发表回答