我如何检查字素是否是一个字母(或一些经常在单词中使用的东西,如象形文字)?
查看 Elixir 的 String
后文档我看到的唯一方法是检查是否 String.downcase
和 String.upcase
返回相同的字符串。如果他们这样做,那么字素就不是用在单词中的东西。
我就是这样做的,但肯定应该有更简单的方法吗?
defmodule Words do
defp all_letters_uppercase?(string) do
String.upcase(string) == string
end
defp all_letters_downcase?(string) do
String.downcase(string) == string
end
defp contains_letter?(string) do
not (all_letters_uppercase?(string) and all_letters_downcase?(string))
end
def single_grapheme?(string) do
with graphemes = String.graphemes(string)
do
length(graphemes) == 1 and hd(graphemes) == string
end
end
@doc """
Check whether string is a single letter.
"""
def letter?(string) do
single_grapheme?(string) and contains_letter?(string)
end
end
更新:我的代码不适用于日语字母
iex(35)> Words.letter?("グ")
false
最佳答案
您可以使用正则表达式来检查某些 unicode 功能,其中之一是 \p{Letter}
, 或 \p{L}
简称。您可能想要添加 \p{Mark}*
, 或 \p{M}*
还匹配多个以下组合变音符号。这将与 String.graphemes/1
中的逻辑非常匹配。 .请务必添加 u
正则表达式后的修饰符以启用这些 Unicode 功能。例如:
iex> String.match?("グ", ~r/\A\p{L}\p{M}*\z/u)
true
另见 http://erlang.org/doc/man/re.html , “Unicode 字符属性”部分和 http://www.regular-expressions.info/unicode.html#grapheme .
关于unicode - 如何检查字素是否是字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36599269/