模块:Utils/String:修订间差异
来自「荏苒之境」
无编辑摘要 |
无编辑摘要 |
||
第1行: | 第1行: | ||
local utils = {} | local utils = {} | ||
utils.replace = function(str, this, that, count) | utils.replace = function(str, this, that, count) | ||
第61行: | 第57行: | ||
utils.expand_xml_noattr = function(str, tag) | utils.expand_xml_noattr = function(str, tag) | ||
return utils.sub_xml_noattr(str, tag, "%1") | return utils.sub_xml_noattr(str, tag, "%1") | ||
end | |||
utils.escape_regex = function(str) | |||
return string.gsub(str, "[%(%)%.%%%+%-%*%?%[%^%$%]]", "%%%1") | |||
end | |||
utils.escape_url = function(str) | |||
local res = string.gsub(str, "([^%w%. %-])", function(c) | |||
return string.format("%%%02X", string.byte(c)) | |||
end) | |||
return res | |||
end | end | ||
第76行: | 第83行: | ||
utils.escape_sql = function(str) | utils.escape_sql = function(str) | ||
local res = string.gsub(str, "([\\\'\"\\0\b\n\r\t\26])", SQL_ESCAPE_MAP) | local res = string.gsub(str, "([\\\'\"\\0\b\n\r\t\26])", SQL_ESCAPE_MAP) | ||
return res | return res |
2025年8月24日 (日) 14:43的最新版本
此模块的文档可以在模块:Utils/String/doc创建
local utils = {}
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
utils.escape_regex = function(str)
return string.gsub(str, "[%(%)%.%%%+%-%*%?%[%^%$%]]", "%%%1")
end
utils.escape_url = function(str)
local res = string.gsub(str, "([^%w%. %-])", function(c)
return string.format("%%%02X", string.byte(c))
end)
return res
end
local SQL_ESCAPE_MAP = {
["\\"] = "\\\\",
["'"] = "\\'",
["\""] = "\\\"",
["\0"] = "\\0",
["\b"] = "\\b",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["\26"] = "\\Z",
}
utils.escape_sql = function(str)
local res = string.gsub(str, "([\\\'\"\\0\b\n\r\t\26])", SQL_ESCAPE_MAP)
return res
end
return utils