Lua:字符类型

Red*_*oud 3 lua char

我需要一个函数

\n\n
function getCharType(c)\n  local i = string.byte(c) -- works only for 1 byte chars\n  if (i > 48) and (i < 57) then return 1 end\n  if (i > 97) and (i < 122) then return 2 end\n  return 0\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

应该返回

\n\n
2 - if c is a letter\n1 - if c is a digit\n0 - if c is  a symbol (anything else)\n
Run Code Online (Sandbox Code Playgroud)\n\n

c 本身已经是小写字符:charType = getCharType(string.lower(Character))。如果可以使用 Unicode 字符就好了。

\n\n

与上面的getCharType("\xc3\xb6") 是0。

\n

cyc*_*ist 5

要确定非 ASCII 字符是大写字母还是小写字母还是数字,您需要 Unicode 数据。维基百科上的Module:Unicode data有一个类似的函数,它使用Module:Unicode data/category(Unicode 字符通用类别的数据)。

\n\n

这是lookup_category来自 Module:Unicode data 的函数的改编。我没有包含 Unicode 数据(模块:Unicode 数据/类别);您必须从上面的链接复制它。

\n\n
local category_data -- set this variable to the table in Module:Unicode data/category above\nlocal floor = math.floor\nlocal function binary_range_search(code_point, ranges)\n    local low, mid, high\n    low, high = 1, #ranges\n    while low <= high do\n        mid = floor((low + high) / 2)\n        local range = ranges[mid]\n        if code_point < range[1] then\n            high = mid - 1\n        elseif code_point <= range[2] then\n            return range\n        else\n            low = mid + 1\n        end\n    end\n    return nil\nend\n\nfunction get_category(code_point)\n    if category_data.singles[code_point] then\n        return category_data.singles[code_point]\n    else\n        local range = binary_range_search(code_point, category_data.ranges)\n        return range and range[3] or "Cn"\n    end\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

该函数get_category采用代码点(数字)并返回常规类别的名称。我猜你感兴趣的类别是Nd(数字,十进制数字)和以(字母)开头的类别L

\n\n

您将需要一个将字符转换为代码点的函数。如果文件采用 UTF-8 编码并且您使用的是 Lua 5.3,则可以使用该utf8.codepoint函数:get_category(utf8.codepoint(\'\xc3\xb6\'))will result in \'Ll\'. 您可以将类别代码转换为上面的函数使用的数值:function category_to_number(category) if category == "Nd" then return 1 elseif category:sub(1, 1) == "L" then return 2 else return 0 end end

\n