跳转到内容
打开/关闭菜单
打开/关闭外观设置菜单
打开/关闭个人菜单
未登录
登录后可编辑和发表评论。

Module:Strings

来自Vocawiki

此模块的文档可以在Module:Strings/doc创建

local s_sub = string.sub
local s_find = string.find

local p = {}

local REMOVE_EMPTY_PREFIXS = {
	[true] = true,
	['^'] = true,
	['^$'] = true,
}
local REMOVE_EMPTY_SUFFIXS = {
	[true] = true,
	['$'] = true,
	['^$'] = true,
}

--- 用给定的pattern分割字符串
---@param str string | number # 被分割的字符串
---@param sep string # pattern,同string.find等函数的第二个参数
---@param remove_empty? boolean | '^' | '$' | '^$' # 是否移除结果中的空字符串。true表示移除所有(包括中间的),'^'移除开头,'$'移除结尾,'^$'移除开头和结尾,false不移除
function p.split(str, sep, remove_empty)
	local out = {}
	local last = 1
	local start, stop = s_find(str, sep, last)

	if start == 1 and REMOVE_EMPTY_PREFIXS[remove_empty] then
		-- skip empty string at the beginning
		last = stop + 1
		start, stop = s_find(str, sep, start <= stop and last or (last + 1))
	end

	while start do
		local sub = s_sub(str, last, start - 1)
		if not (sub == '' and remove_empty == true) then
			out[#out + 1] = sub
		end
		last = stop + 1
		-- when start > stop (stop == start - 1), empty string is matched
		start, stop = s_find(str, sep, start <= stop and last or (last + 1))
	end

	if last <= #str or not REMOVE_EMPTY_SUFFIXS[remove_empty] then
		out[#out + 1] = s_sub(str, last)
	end
	return out
end

return p