【步兵 lua】匹配模式 之 花式split

【步兵 lua】匹配模式 之 花式split by EOS.

練習匹配模式自己寫的一些東西,拿出來分享一下,希望對大家有幫助=。=

代碼

local str = "a/b/c/d//e"

print"\nsplit first:"
local iter = string.gmatch(str, "[^/]+")
for v in iter do
    print(v, type(v))
end


print"\nsplit second:"
local iter = string.gmatch(str, "(.-)/")
local last = string.match(str, ".*/(.*)")
for v in iter do
    print(v, type(v))
end
print(last, type(last))


print"\nsplit third:"
local str2 = string.gsub(str, "(//)",function(p1)
    if(p1 == "")then p1 = "nil"end
    return "/nil/"
end)
for v in string.gmatch(str2, "[^/]+") do
    print(v, type(v))
end


print"\nsplit fourth:"
local str2 = string.gsub(str, "(.-)/",function(p1, p2)
    if(p1 == "")then p1 = "nil"end
    return p1.."/"
end)
for v in string.gmatch(str2, "[^/]+") do
    print(v, type(v))
end


print"\nsplit fifth:"
local str2 = str
local arr = {}
while true do
    local b,e = string.find(str2, "/")
    if b == nil then 
        table.insert(arr, str2)
        break
    end
    table.insert(arr, string.sub(str2, 1, e-1))
    str2 = string.sub(str2, e+1, -1)
end
for k,v in ipairs(arr) do
    print(v, type(v))
end

print"\nsplit sixth:"
local arr = {}
local str2 = str
while string.find(str2, "/") do
    arr[#arr+1] = string.match(str2, "(.-)/")
    str2 = string.gsub(str2, "(.-)/", "", 1)
end
arr[#arr+1] = str2
for k,v in pairs(arr) do
    print(v, type(v))
end

輸出

這裏寫圖片描述

上班ING,偷偷上傳的。。 = 3= 幹活去了

See Again~
之前
真愛無價,歡迎打賞~
讚賞碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章