lua - Lua:字符的类型
问题描述
我需要一个函数
function getCharType(c)
local i = string.byte(c) -- works only for 1 byte chars
if (i > 48) and (i < 57) then return 1 end
if (i > 97) and (i < 122) then return 2 end
return 0
end
应该返回
2 - if c is a letter
1 - if c is a digit
0 - if c is a symbol (anything else)
c 本身已经是一个小写字符:charType = getCharType(string.lower(Character))
. 如果 Unicode 字符是可能的,那很好。
以上getCharType("ö")
为0。
解决方案
要确定非 ASCII 字符是大写字母还是小写字母或数字,您需要 Unicode 数据。Module:Unicode data on Wikipedia 有一个类似这样的函数,它使用Module:Unicode data/category(Unicode 字符的通用类别的数据)。
lookup_category
这是对来自 Module:Unicode 数据的函数的改编。我没有包含 Unicode 数据(模块:Unicode 数据/类别);您必须从上面的链接中复制它。
local category_data -- set this variable to the table in Module:Unicode data/category above
local floor = math.floor
local function binary_range_search(code_point, ranges)
local low, mid, high
low, high = 1, #ranges
while low <= high do
mid = floor((low + high) / 2)
local range = ranges[mid]
if code_point < range[1] then
high = mid - 1
elseif code_point <= range[2] then
return range
else
low = mid + 1
end
end
return nil
end
function get_category(code_point)
if category_data.singles[code_point] then
return category_data.singles[code_point]
else
local range = binary_range_search(code_point, category_data.ranges)
return range and range[3] or "Cn"
end
end
该函数get_category
接受一个代码点(一个数字)并返回通用类别的名称。我猜你感兴趣的类别是Nd
(数字,十进制数字)和以L
(字母)开头的类别。
您将需要一个将字符转换为代码点的函数。如果文件以 UTF-8 编码并且您使用的是 Lua 5.3,则可以使用utf8.codepoint
函数:get_category(utf8.codepoint('ö'))
将导致'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
.
推荐阅读
- protractor - 如何在量角器中上下滚动
- angular - 在启用 Ivy 的情况下构建 monorepo Angular9 库是不是一个坏主意
- php - 将绝对部分路由到codeigniter中的控制器
- javascript - div 扩展动画最大高度不起作用。高度始终为 0
- amazon-web-services - cassandra 如何对多区域设置中的区域故障做出反应
- c# - “索引超出范围”异常在 DataGridView SelectionChanged 事件中引发而 FormLoad
- ruby-on-rails - #<# 的未定义方法“路径名”
我更新了项目的 Ruby 和 Rails 版本。
红宝石
2.2.3
->2.5.1
导轨
4.1.8
->5.1.7
现在,当我启动服务器时,出现此错误:
F, [2020-02-03T11:15:49.912
- arrays - RISC-V 循环遍历单词数组
- linux - 什么软件包在 RHEL8 中提供 systemd-networkd?
- vb.net - DateTime.Parse:无法提供值:找不到主机值