【问题标题】:Convert unicode codepoint to string character in Ruby在Ruby中将unicode代码点转换为字符串字符
【发布时间】:2011-10-22 00:51:20
【问题描述】:

我有来自 unicode 数据库的这些值,但我不确定如何将它们转换为人类可读的形式。这些到底叫什么?

他们在这里:

  • U+2B71F
  • U+2A52D
  • U+2A68F
  • U+2A690
  • U+2B72F
  • U+2B4F7
  • U+2B72B

如何将这些转换为可读的符号?

【问题讨论】:

  • @Gabriel 我不知道你想对 UCS-2 说什么?这不是“符号编码”。这是一个过时的序列化方案,不再适用于 Unicode,并且自 Unicode 1.1 以来就不再适用,这是无限永远的。

标签: ruby string unicode utf-8


【解决方案1】:

怎么样:

# Using pack
puts ["2B71F".hex].pack("U")

# Using chr
puts (0x2B71F).chr(Encoding::UTF_8)

在 Ruby 1.9+ 中你也可以这样做:

puts "\u{2B71F}"

\u{} 转义序列可用于解码 Unicode 代码点。

【讨论】:

  • 您也可以只使用十六进制文字:[0x2B71F].pack 'U'
【解决方案2】:

U+2B71F 这样的unicode 符号被称为codepoint

unicode 系统为多种世界语言、科学符号、货币等中的每个字符定义了一个唯一的codepoint。这个字符集正在稳步增长。

例如,U+221E 是无穷大。

codepoints 是十六进制数字。每个字符总是定义一个数字。

有很多方法可以在内存中安排它。这称为encoding,其中常见的是UTF-8UTF-16。来回转换定义明确。

在这里,您很可能正在寻找将 unicode codepoint 转换为 UTF-8 字符。

codepoint = "U+2B71F"

您需要提取U+ 之后的十六进制部分并仅获得2B71F。这将是第一次集体捕获。 See this.

codepoint.to_s =~ /U\+([0-9a-fA-F]{4,5}|10[0-9a-fA-F]{4})$/

而你的 UTF-8 字符将是:

utf_8_character = [$1.hex].pack("U")

参考资料:

  1. Convert Unicode codepoints to UTF-8 characters with Module#const_missing
  2. Tim Bray on the goodness of unicode
  3. Joel Spolsky - The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
  4. Dissecting the Unicode regular expression

【讨论】:

  • codepoint 是“U+2B71F”。为了从中提取“2B71F”,我将它与一个 unicode 正则表达式匹配。正则表达式中定义了一组用于提取“2B71F”。比赛结束后,如果有的话,在这种情况下你可以用 $1 来引用它。 Follow this rubular permalink to see the regex in action.
  • 我在 SO 上读过的关于 unicode、utf-8 代码点、字符集、编码等的最佳答案之一......而且链接非常棒。 joelonsoftware.com/articles/Unicode.html 特别适合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
相关资源
最近更新 更多