【发布时间】:2013-04-05 11:05:55
【问题描述】:
第一个问题。 Lua中确定字符串中的最后一个字符是否不是多字节的最简单方法是什么。或者从字符串中删除最后一个字符的最简单方法是什么。
以下是有效字符串的示例,以及我希望函数的输出是什么
hello there --- result should be: hello ther
anñ --- result should be: an
כראע --- result should be: כרא
ㅎㄹㅇㅇㅅ --- result should be: ㅎㄹㅇㅇ
我需要类似的东西
function lastCharacter(string)
--- some code which will extract the last character only ---
return lastChar
end
或者如果它更容易
function deleteLastCharacter(string)
--- some code which will output the string minus the last character ---
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
【问题讨论】:
-
尝试使用正则表达式
^(.*).$,然后返回第一个捕获组。我不太确定如何在 Lua 中做到这一点,但我猜这会做到。 -
对不起:使用表达式
^(.*)(.)$,然后返回第一个捕获组删除最后一个字符,或返回第二个组检索最后一个字母。 -
你的模式看起来相当不错。尝试删除
+并在末尾添加$。+将确保您不会拾取额外的单字节字符,$将您的模式锚定到字符串的末尾。但是,string.len会给出字节数,因此lastc将只包含最后一个字节,而不是整个最后一个字符。 -
string.sub(str, stringLength,stringLength)确实返回了str中的最后一个字符。请确保不要将变量命名为string,因为这与string表冲突。另外,您能否详细说明多字节字符的含义? -
@Netfangled 是的,不,不起作用。它返回最后一个字节。对于第三个和第四个示例,这不是整个最后一个字符(如果是正确的 UTF-8 编码,第二个也不是)。它真的不能工作,因为 Lua 的内置
string库没有 Unicode 的概念......它的字符串只包含字节,由你来理解它们。
标签: regex lua coronasdk multibyte