Lua学习教程之 spilt函数的实现

来源:互联网 发布:网络女歌手依然的照片 编辑:程序博客网 时间:2024/04/29 03:08

在java中,很容易使用正则表达式将一个字符串分割,下面使用Lua实现spilt函数

方法一:

local spilt=function (str,pattern)local ret={};local _pattern= "[^"..pattern.. "]+";for s in string.gfind(str,_pattern) dotable.insert(ret,s);endreturn ret;end


方法二:

local spilt = function(str,pattern)    local ret= {}    string.gsub(str, "[^".. pattern .."]+", function(item) table.insert(ret, item) end )    return  ret;end



测试代码如下:

local a="a.zip;b.zip";local f=spilt(a,";");for _, s in ipairs(f) do    print(s)end

打印结果:

a.zip

b.zip



注意:lua可能因为库版本的问题,gsub不能用时改为gmatch即可

0 2
原创粉丝点击