Lua 標準庫未提供字符串分割函數,開發者常需自行實現。本文提供一個健壯、支持限制分割數量的 Split 函數實現並逐行解析。
function Split(str, delim, maxNb)
-- 參數校驗
if string.find(str, delim) == nil then
return { str } -- 無分隔符,返回原字符串單元素表
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- 0 表示無限制
end
local result = {}
local pat = "(.-)" .. delim .. "()" -- 捕獲分隔符前內容及分隔符後位置
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- 處理最後一段
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
"(.-)" .. delim .. "()"。(.-) 非貪婪匹配任意字符(分隔符前內容),() 捕獲當前位置(分隔符後起始索引)。string.gfind (Lua 5.1) 或 string.gmatch (Lua 5.2+) 逐個匹配分隔符,提取字段與下一開始位置。maxNb 時提前終止循環。-- 基礎分割
print(table.concat(Split("a,b,c", ","), "|")) -- a|b|c
-- 限制分割數
print(table.concat(Split("a,b,c,d", ",", 2), "|")) -- a|b|c,d
-- 無分隔符
print(table.concat(Split("abc", ","), "|")) -- abc
可使用 string.gmatch 寫更簡潔版本:
function split(str, sep)
local t = {}
for s in string.gmatch(str, "([^" .. sep .. "]+)") do
table.insert(t, s)
end
return t
end
但該版本不支持多字符分隔符與限制數量,視場景選擇。
Split 函數展示了 Lua 模式匹配的強大與靈活。理解其原理,可根據具體需求(保留空字段、轉義分隔符、正則分隔符)靈活定製。