Lua按指定字符分隔字符串的3种方法

1.

function split( str,reps )
    local resultStrList = {}
    string.gsub(str,'[^'..reps..']+',function ( w )
        table.insert(resultStrList,w)
    end)
    return resultStrList
end

string库的gsub函数,共三个参数:
1. str是待分割的字符串
2. '[^'..reps..']+'是正则表达式,查找非reps字符,并且多次匹配
3. 每次分割完的字符串都能通过回调函数获取到,w参数就是分割后的一个子字符串,把它保存到一个table中

2.

function string.split(input, delimiter)
    input = tostring(input)
    delimiter = tostring(delimiter)
    if (delimiter=='') then return false end
    local pos,arr = 0, {}
    for st,sp in function() return string.find(input, delimiter, pos, true) end do
        table.insert(arr, string.sub(input, pos, st - 1))
        pos = sp + 1
    end
    table.insert(arr, string.sub(input, pos))
    return arr
end

3.

function getSplitStr(logStr,breakpointsStr,t)
    local i = 0
    local j = 1
    local z = string.len(breakpointsStr)
    while true do
        i = string.find(logStr, breakpointsStr, i + 1)  -- 查找下一行
        if i == nil then
            table.insert(t, string.sub(logStr,j,-1))
            break 
        end
        table.insert(t, string.sub(logStr,j,i - 1))
        j = i + z
    end 
    return t
end

你可能感兴趣的:(Lua,lua)