如何判断一个字符是否是汉字

发布于 2024-08-30 12:52:53 字数 27 浏览 3 评论 0原文

如何使用ruby判断一个字符是否是汉字?

How to determine if a character is a Chinese character using ruby?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆光飞翔i 2024-09-06 12:52:55

红宝石1.9

#encoding: utf-8   
 "漢" =~ /\p{Han}/

Ruby 1.9

#encoding: utf-8   
 "漢" =~ /\p{Han}/
不弃不离 2024-09-06 12:52:55

关于 Ruby 编码的有趣文章:http://blog.grayproducts.net/articles/bytes_and_characters_in_ruby_18 (这是一个系列的一部分 - 也请检查文章开头的目录)

我以前没有使用过中文字符,但这似乎是 unicode 支持的列表: http://en.wikipedia.org/wiki/List_of_CJK_Unified_Ideographs 。另请注意,它是一个统一的系统,包括日文和韩文字符(某些字符在它们之间共享) - 不确定您是否可以区分哪些只是中文。

我认为你可以通过在字符串 str 和索引为 n 的字符上调用它来检查它是否是 CJK 字符:

def check_char(str, n)
  list_of_chars = str.unpack("U*")
  char = list_of_chars[n]
  #main blocks
  if char >= 0x4E00 && char <= 0x9FFF
    return true
  end
  #extended block A
  if char >= 0x3400 && char <= 0x4DBF
    return true
  end
  #extended block B
  if char >= 0x20000 && char <= 0x2A6DF
    return true
  end
  #extended block C
  if char >= 0x2A700 && char <= 0x2B73F
    return true
  end
  return false
end

An interesting article on encodings in Ruby: http://blog.grayproductions.net/articles/bytes_and_characters_in_ruby_18 (it's part of a series - check the table of contents at the start of the article also)

I haven't used chinese characters before but this seems to be the list supported by unicode: http://en.wikipedia.org/wiki/List_of_CJK_Unified_Ideographs . Also take note that it's a unified system including Japanese and Korean characters (some characters are shared between them) - not sure if you can distinguish which are Chinese only.

I think you can check if it's a CJK character by calling this on string str and character with index n:

def check_char(str, n)
  list_of_chars = str.unpack("U*")
  char = list_of_chars[n]
  #main blocks
  if char >= 0x4E00 && char <= 0x9FFF
    return true
  end
  #extended block A
  if char >= 0x3400 && char <= 0x4DBF
    return true
  end
  #extended block B
  if char >= 0x20000 && char <= 0x2A6DF
    return true
  end
  #extended block C
  if char >= 0x2A700 && char <= 0x2B73F
    return true
  end
  return false
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文