Capil ka isi

Modul:string/patternEscape

Matan Wiktionary

Dokumentasi untuk modul ini dapat dibuat di Modul:string/patternEscape/doc

-- Imported from enwiktionary
-- Source: https://en.wiktionary.org/wiki/Module:string/patternEscape
-- License: CC BY-SA

local gsub = string.gsub

local chars
local function get_chars()
	chars, get_chars = {
		["\000"] = "%z", ["$"] = "%$", ["%"] = "%%", ["("] = "%(", [")"] = "%)",
		["*"] = "%*", ["+"] = "%+", ["-"] = "%-", ["."] = "%.", ["?"] = "%?",
		["["] = "%[", ["]"] = "%]", ["^"] = "%^",
	}, nil
	return chars
end

--[==[Escapes the magic characters used in a pattern: {$%()*+-.?[]^}, and converts the null character to {%z}. For example, {"^$()%.[]*+-?\0"} becomes {"%^%$%(%)%%%.%[%]%*%+%-%?%z"}. This is necessary when constructing a pattern involving arbitrary text (e.g. from user input).]==]
return function(str)
	return (gsub(str, "[%z$%%()*+%-.?[%]^]", chars or get_chars()))
end