lua常用字符分离(gmatch)及替换(gsub)模式实例
程序员文章站
2022-03-18 18:08:44
...
lua常用字符分离(gmatch)及替换(gsub)模式实例
- 分离字符
local function stringSplit(param)--分离字符
local pattern = {}
if string.find(param, "\n") ~= nil then
for k, v in param:gmatch('([^=]+)=([^\n]*)\n?') do
--print(k, v)
pattern[k] = v
end
else
for k, v in param:gmatch('([^=]+)=([^,]*),?') do
--print(k," ", v)
pattern[k] = v
end
end
return pattern
end
-- 分离字符
local function StringToTable(s)
local tb = {}
for utfChar in string.gmatch(s, "[%z\1-\127\194-\244][\128-\191]*") do
table.insert(tb, utfChar)
end
return tb
end
local function test() --分离字符
local s="xx千里之外12"
for k,v in pairs(StringToTable(s)) do
print("v1:",v," k:",k)
end
local param= "0==123\nWOOD==555\nIRON==4\nSTONE==9\nFOOD==11"
local pattern={}
for k, v in pairs(stringSplit(param)) do
pattern[k] = v
print("k:",k," v:",v)
end
end
- 字符替换
local function test2() --字符替换
local y="{AA},{BB}"
local conKeyName={
AA=3,
BB=6,
}
local cc=y:gsub('{([^}]+)}',conKeyName) --字符替换
print("cc:",cc) --3,6
local formatted=-123456789
formatted= string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') --字符替换
print("formatted:",formatted) --123456,789
end