"d̪".chars.to_a
给我
["d"," ̪"]
我该如何让Ruby按字形分割字符串?
["d̪"]
"d̪".chars.to_a
["d"," ̪"]
["d̪"]
编辑:正如@michau的答案所指出的那样,Ruby 2.5引入了grapheme_clusters
方法,以及each_grapheme_cluster
如果你只想迭代/枚举而不一定创建一个数组。
在 Ruby 2.0 或更高版本中,你可以使用str.scan /\X/
> "d̪".scan /\X/
=> ["d̪"]
> "d̪d̪d̪".scan /\X/
=> ["d̪", "d̪", "d̪"]
# Let's get crazy:
> str = 'Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'
> str.length
=> 75
> str.scan(/\X/).length
=> 6
如果由于某种原因您想要匹配字形边界,可以在正则表达式中使用(?=\X)
,例如:
> "d̪".split /(?=\X)/
=> ["d̪"]
如果由于某些原因你无法使用\X
,Rails中包含的ActiveSupport也有一种方法:
ActiveSupport::Multibyte::Unicode.unpack_graphemes("d̪").map { |codes| codes.pack("U*") }
"d̪".grapheme_clusters # => ["d̪"]
使用 unicode.gem 中的 Unicode::text_elements
,该函数在 http://www.yoshidam.net/unicode.txt 中有详细说明。
irb(main):001:0> require 'unicode'
=> true
irb(main):006:0> s = "abčd̪é"
=> "abčd̪é"
irb(main):007:0> s.chars.to_a
=> ["a", "b", "č", "d", "̪", "é"]
irb(main):009:0> Unicode.nfc(s).chars.to_a
=> ["a", "b", "č", "d", "̪", "é"]
irb(main):010:0> Unicode.nfd(s).chars.to_a
=> ["a", "b", "c", "̌", "d", "̪", "e", "́"]
irb(main):017:0> Unicode.text_elements(s)
=> ["a", "b", "č", "d̪", "é"]
s.scan(/\X/)
或s.grapheme_clusters
。 - michauRuby2.0
str = "d̪"
char = str[/\p{M}/]
other = str[/\w/]