【问题标题】:How to specify Regexp for unicode cyrillic characters in Ruby 1.9如何在 Ruby 1.9 中为 unicode 西里尔字符指定正则表达式
【发布时间】:2010-04-27 14:06:18
【问题描述】:
#coding: utf-8
str2 = "asdfМикимаус"
p str2.encoding #<Encoding:UTF-8> 
p str2.scan /\p{Cyrillic}/ #found all cyrillic characters
str2.gsub!(/\w/u,'') #removes only latin characters
puts str2

问题是为什么\w 忽略西里尔字符?

我已经从http://rubyinstaller.org/ 安装了最新的 ruby​​ 包。 这是我对ruby -v的输出

ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-mingw32]

据我所知 1.9 oniguruma 正则表达式库完全支持 unicode 字符。

【问题讨论】:

  • 在 Linux (ruby 1.9) 上 gsub 删除所有字符 - irb(main):006:0> str2.gsub(/\w/u,'') => ""
  • @aaz:不应该(见我的回答);可能你有旧版本?
  • 我会将这个问题重命名为“如何在 Ruby 1.9 中为 unicode 字符指定正则表达式”,因为这与 win32 或(仅)西里尔文无关。
  • 你是对的。它是 ruby​​ 1.9.1p0 中的一个错误,在 ruby​​ 1.9.1p376 中一切正常

标签: ruby regex unicode encoding character-properties


【解决方案1】:

这是在Ruby documentation 中指定的:\w 等效于 [a-zA-Z0-9_],因此不针对任何 unicode 字符。

您可能想改用 [[:alnum:]],它包括所有 unicode 字母和数字字符。还要检查[[:word:]][[:alpha:]]

【讨论】:

  • 顺便说一句,我们要感谢 Run Paint Run Run 编写此文档。
猜你喜欢
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多