Module:Util/strings/split: Difference between revisions

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search
(Created page with "local function split(text, pattern, plain) pattern = pattern or "%s*,%s*" local ret = {} if pattern == "" then for m in string.gmatch(text, "([%z\1-\127\194-\244][\128-\191]*)") do ret[#ret+1] = m end return ret end local i = 1 while true do local startIndex, endIndex = string.find(text, pattern, i, plain) local s = string.sub(text, i, startIndex and startIndex-1) table.insert(ret, s) if startIndex == nil then break end i = endIndex...")
 
No edit summary
 
Line 1: Line 1:
local function split(text, pattern, plain)
local function split(text, pattern)
pattern = pattern or "%s*,%s*"
pattern = pattern or "%s*,%s*"
local ret = {}
local ret = {}
Line 12: Line 12:
local i = 1
local i = 1
while true do
while true do
local startIndex, endIndex = string.find(text, pattern, i, plain)
local startIndex, endIndex = string.find(text, pattern, i)
local s = string.sub(text, i, startIndex and startIndex-1)
local s = string.sub(text, i, startIndex and startIndex-1)
table.insert(ret, s)
table.insert(ret, s)

Latest revision as of 21:14, 5 May 2024

split(str, [pattern])

A performant alternative to mw.text.split.

Parameters

Returns

  • A table of the split strings.

Examples

#InputOutputResult
1
split(" foo,    bar,baz ")
{" foo", "bar", "baz "}
Green check.svg
2
split("foo bar baz", " ")
{"foo", "bar", "baz"}
Green check.svg
Support for Unicode strings
3
split("アイウエオ", "")
{"ア", "イ", "ウ", "エ", "オ"}
Green check.svg
4
split("グタンバチの祠, インイサの祠")
{"グタンバチの祠", "インイサの祠"}
Green check.svg

local function split(text, pattern)
	pattern = pattern or "%s*,%s*"
	local ret = {}

	if pattern == "" then
		for m in string.gmatch(text, "([%z\1-\127\194-\244][\128-\191]*)") do
          ret[#ret+1] = m
		end
		return ret
	end

	local i = 1
	while true do
		local startIndex, endIndex = string.find(text, pattern, i)
		local s = string.sub(text, i, startIndex and startIndex-1)
		table.insert(ret, s)
		if startIndex == nil then
			break
		end
		i = endIndex+1
	end
	return ret
end

return split