在Lua中检测最后一个字符是否不是多字节。

第一个问题。在 Lua 中,最简单的方法是确定字符串中的最后一个字符是否不是多字节字符。或者删除字符串中最后一个字符的最简单方法是什么。

下面是有效字符串的示例,以及我希望函数的输出是什么

hello there     --- 结果应该是:   hello ther
anñ             --- 结果应该是:   an
כראע            --- 结果应该是:   כרא
ㅎㄹㅇㅇㅅ       --- 结果应该是:   ㅎㄹㅇㅇ

我需要像这样的东西:

function lastCharacter(string)
    --- 一些仅提取最后一个字符的代码 ---
    return lastChar
end

或者如果更容易

function deleteLastCharacter(string)
--- 一些输出减去最后一个字符的字符串的代码 ---
    return newString
end

这是我走的路线

local function lastChar(string)
    local stringLength = string.len(string)
    local lastc = string.sub(string,stringLength,stringLength)
    if lastc is a multibyte character then
        local wordTable = {}
        for word in string:gmatch("[\33-\127\192-\255]+[\128-\191]*") do
            wordTable[#wordTable+1] = word
        end
    lastc = wordTable[#wordTable]
end
    return lastc
end
点赞
用户1442917
用户1442917

根据prapin 这里 的解决方案:

function lastCharacter(str)
  return str:match("[%z\1-\127\194-\244][\128-\191]*$")
end

然后可以获取返回值的长度来判断它是否是多字节字符,也可以使用gsub功能从字符串中删除它:

function deleteLastCharacter(str)
  -- make sure to add "()" around gsub to force it to return only one value
  return(str:gsub("[%z\1-\127\194-\244][\128-\191]*$", ""))
end

for _, str in pairs{"hello there", "anñ", "כראע"} do
  print(str, " -->-- ", deleteLastCharacter(str))
end

请注意,这些模式仅适用于有效的UTF-8字符串。 如果你有可能无效的字符串,则可能需要应用更复杂的逻辑

2013-04-12 21:14:04
用户33252
用户33252

以下是一个另外的做法,它展示了如何通过 utf8 迭代字符串中的字符:

function butlast (str)
    local i,j,k = 1,0,-1
    while true do
        s,e = string.find(str,".[\128-\191]*",i)
        if s then
            k = j
            j = e
            i = e + 1
        else break end
    end
    return string.sub(str,1,k)
end

使用示例:

> return butlast"כראע"
כרא
> return butlast"ㅎㄹㅇㅇㅅ"
ㅎㄹㅇㅇ
> return butlast"anñ"
an
> return butlast"hello there"
hello ther
>

2013-04-12 21:14:41