模块:Utils/String

来自「荏苒之境」
Sicusa留言 | 贡献2025年8月24日 (日) 02:24的版本

此模块的文档可以在模块:Utils/String/doc创建

local utils = {}

utils.escape_regex = function(str)
	return string.gsub(str, "[%(%)%.%%%+%-%*%?%[%^%$%]]", "%%%1")
end

utils.replace = function(str, this, that, count)
	return string.gsub(str, utils.escape_regex(this), that:gsub("%%", "%%%%"), count)
end

utils.trim = function(str)
	local res = string.gsub(str, "^%s*(.-)%s*$", "%1")
	return res
end

utils.split = function(str, sep)
	if sep == nil then
		sep = "%s"
	end
	local t = {}
	for str in string.gmatch(str, "([^"..sep.."]+)") do
		t[#t+1] = str
	end
	return t
end

utils.unword = function(str)
	local t = {}
	for str in string.gmatch(str, "([^%s]+)") do
		t[#t+1] = str
	end
	return t
end

utils.unlines = function(str, alternative)
	local regex = alternative
		and "([^"..alternative.."]*)(["..alternative.."]?)"
		or "([^\n]*)(\n?)"
	local t = {}
    for line, newline in string.gmatch(str, regex) do
    	if line == "" and newline == "" then
    		break
    	elseif string.sub(line, #line) == "\r" then
    		line = string.sub(line, 1, #line - 1)
    	end
        t[#t+1] = line
    end
    return t
end

utils.match_xml_noattr = function(str, tag)
	local res = string.match(str, "<"..tag..">(.-)</"..tag..">")
	return res
end

utils.sub_xml_noattr = function(str, tag, rep)
	local res = string.gsub(str, "<"..tag..">(.-)</"..tag..">", rep)
	return res
end

utils.expand_xml_noattr = function(str, tag)
	return utils.sub_xml_noattr(str, tag, "%1")
end

local SQL_ESCAPE_MAP = {
    ["\\"] = "\\\\",
    ["'"] = "\\'",
    ["\""] = "\\\"",
    ["\0"] = "\\0",
    ["\b"] = "\\b",
    ["\n"] = "\\n",
    ["\r"] = "\\r",
    ["\t"] = "\\t",
    ["\26"] = "\\Z",
}

utils.escape_sql = function(str)
    if not str then return nil end
    local res = string.gsub(str, "([\\\'\"\\0\b\n\r\t\26])", SQL_ESCAPE_MAP)
    return res
end

return utils