ruby 正则表达式 匹配中文

1.puts /[一-龥]+/.match("this is 中文") =>中文

2.str2="123中文"

puts /\p{Han}+/u.match(str2)

文本编码格式:utf-8

文件第一行:#encoding:utf-8

require "rubygems"

require "iconv"

print Iconv.iconv("GBK","UTF-8",/\p{Han}+/u.match("tiantianxin你好angshang天天向上")[0]) =>你好

Ruby 和部分语言可以直接 #{Han} 等方式匹配特定的语言,但是对于某些语言,如 JavaScript,是不可能如此简便的

还有常用的:

  • /\p{Word}+/u 不限于 a-z0-9 的成词字符(就是非标点制表符空格等杂类的字符)
  • /\p{Hiragana,Katakana}+/u 匹配平假名+片假名

适用于中韩日的正则表达式,参考:http://chrisyip.im/post/regular-expression-for-cjk/

学习参考:http://ruby-china.org/topics/5680