我需要做一个简单的字符串拆分,但似乎没有一个函数可以做到这一点,而且我手动测试的方法似乎不起作用。我该怎么做呢?
发布于 2009-09-15 15:59:12
如果要在Lua中拆分字符串,应该尝试使用string.gmatch()或string.sub()方法。如果知道要拆分字符串的索引,请使用string.sub()方法;如果要分析字符串以查找要拆分字符串的位置,请使用string.gmatch()。
使用Lua 5.1 Reference Manual中的string.gmatch()的示例
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
发布于 2009-10-16 18:36:32
下面是函数:
function split(pString, pPattern)
local Table = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pPattern
local last_end = 1
local s, e, cap = pString:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(Table,cap)
end
last_end = e+1
s, e, cap = pString:find(fpat, last_end)
end
if last_end <= #pString then
cap = pString:sub(last_end)
table.insert(Table, cap)
end
return Table
end
它的名称如下:
list=split(string_to_split,pattern_to_match)
例如:
list=split("1:2:3:4","\:")
有关更多信息,请访问此处:
发布于 2013-11-20 23:46:01
我喜欢这个简短的解决方案
function split(s, delimiter)
result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match);
end
return result;
end
https://stackoverflow.com/questions/1426954
复制相似问题