我有一个在Lua中的多字节字符串。
local s = "あいうえお"
如何将字符串拆分为字符串表?
对于英文文本,可以使用以下代码。但是这在多字节情况下无法工作。
local s = "foo bar 123"
local words = {}
for word in s:gmatch("%w+") do
table.insert( words, word )
end
我有一个在Lua中的多字节字符串。
local s = "あいうえお"
如何将字符串拆分为字符串表?
对于英文文本,可以使用以下代码。但是这在多字节情况下无法工作。
local s = "foo bar 123"
local words = {}
for word in s:gmatch("%w+") do
table.insert( words, word )
end
正如其他人所指出的,很难确定你想要做什么:如果在空格处分割不够,请问您要在哪里分割非ASCII字符?
如果您只想为非ASCII字符之间的单个字符进行拆分,则可以尝试以下类似方法:
s = "oink barf 頑張っています"
for word in s:gmatch("[\33-\127\192-\255]+[\128-\191]*") do
print (word)
end
生成:
oink
barf
頑
張
っ
て
い
ま
す
11
(因此在Lua中是\192
–\255
,请记住,在Lua中的字符转义使用十进制),后跟零个或多个“尾随字节”,其最高两位等于10
(在Lua中是\128
–\191
)。首先,从这个stackoverflow问题开始如何在lua中编写unicode符号,RBerteig的答案指向了一个库slnunicode
还在这个stackoverflow问题中提到有没有任何Lua库可以使用utf8编码将字符串转换为字节
如果是UTF-8编码,在Lua 5.3中,您可以像这样使用utf8
库:
local s = "あいうえお"
local words = {}
for _, c in utf8.codes(s) do
table.insert(words, utf8.char(c))
end