Lua - 从文件中读取一个 UTF-8 字符

Lua - read one UTF-8 character from file

是否可以从文件中读取一个UTF-8字符?

file:read(1) return 奇怪的字符,当我打印它时。

function firstLetter(str)
  return str:match("[%z-74-4][8-1]*")
end

函数returns 字符串str 中的一个UTF-8 字符。我需要以这种方式读取一个 UTF-8 字符,但是从输入文件中读取(不想将某些文件读取到内存中 - 通过 file:read("*all"))

问题与此非常相似post: Extract the first letter of a UTF-8 string with Lua

function read_utf8_char(file)
  local c1 = file:read(1)
  local ctr, c = -1, math.max(c1:byte(), 128)
  repeat
    ctr = ctr + 1
    c = (c - 128)*2
  until c < 128
  return c1..file:read(ctr)
end

您需要读取字符,以便您匹配的字符串始终包含四个或更多字符(这将允许您应用您引用的答案中的逻辑)。如果在匹配并删除 UTF-8 字符后长度为 len,则您将从文件中读取 4-len 个字符。

ZeroBrane Studio 在打印到“输出”面板时将无效的 UTF-8 字符替换为 [SYN] 字符(如屏幕截图所示)。 This blogpost 描述了检测无效 UTF-8 字符(在 Lua 中)背后的逻辑及其在 ZeroBrane Studio 中的处理。

在 UTF-8 编码中,字符的字节数由该字符的第一个字节决定,根据以下 table(取自 RFC 3629

Char. number range  |        UTF-8 octet sequence
   (hexadecimal)    |              (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

如果第一个字节的最高位是“0”,那么这个字符只有一个字节。如果最高位是“110”,则字符有 2 个字节,依此类推。

然后您可以做的是从文件中读取一个字节并确定您需要读取多少个连续字节才能成为完整的 UTF-8 字符:

function get_one_utf8_character(file)

  local c1 = file:read(1)
  if not c1 then return nil end

  local ncont
  if     c1:match("[[=11=]0-7]") then ncont = 0
  elseif c1:match("[2-3]") then ncont = 1
  elseif c1:match("[4-9]") then ncont = 2
  elseif c1:match("[0-7]") then ncont = 3
  else
    return nil, "invalid leading byte"
  end

  local bytes = { c1 }
  for i=1,ncont do
    local ci = file:read(1)
    if not (ci and ci:match("[8-1]")) then
      return nil, "expected continuation byte"
    end
    bytes[#bytes+1] = ci
  end

  return table.concat(bytes)
end