我在努力解决这个问题:
给定两个字符串:
s1 = '/foo/:bar/oof/:rab'
s2 = '/foo/lua/oof/rocks'我想提供以下资料:
s2值的表,在s1中具有相应的名称。在这种情况下,我们需要:{ bar = "lua", rab = "rocks" }我认为这个算法解决了这个问题,但是我想不出如何实现它(可能是使用gmatch):
:索引存储为表的键,相应的值是这些占位符的名称。
使用s1的示例:
局部aux1 ={ "6“= "bar","15”= "rab“}aux1的键作为索引,将s2的值提取到另一个表中:
局部aux2 = {"6“= "lua","15”= "rocks"}发布于 2015-03-01 15:56:30
可能是这样的:
function comp(a,b)
local t = {}
local i, len_a = 0
for w in (a..'/'):gmatch('(.-)/') do
i = i + 1
if w:sub(1,1) == ':' then
t[ -i ] = w:sub(2)
else
t[ i ] = w
end
end
len_a = i
i = 0
local ans = {}
for w in (b..'/'):gmatch('(.-)/') do
i = i + 1
if t[ i ] and t[ i ] ~= w then
return {}
elseif t[ -i ] then
ans[ t[ -i ] ] = w
end
end
if len_a ~= i then return {} end
return ans
end
s1 = '/foo/:bar/oof/:rab'
s2 = '/foo/lua/oof/rocks'
for k,v in pairs(comp(s1,s2)) do print(k,v) end发布于 2016-03-15 22:18:11
另一种解决办法可以是:
s1 = '/foo/:bar/oof/:rab'
s2 = '/foo/lua/oof/rocks'
pattern = "/([^/]+)"
function getStrngTable(_strng,_pattern)
local t = {}
for val in string.gmatch(_strng,_pattern) do
table.insert(t,val)
end
return t
end
local r = {}
t1 = getStrngTable(s1,pattern)
t2 = getStrngTable(s2,pattern)
for k = 1,#t1 do
if (t1[k] == t2[k]) then
r[t1[k + 1]:match(":(.+)")] = t2[k + 1]
end
end表r将具有所需的结果
下面的解决方案也会给出同样的结果:
s1 = '/foo/:bar/oof/:rab'
s2 = '/foo/lua/oof/rocks'
pattern = "/:?([^/]+)"
function getStrng(_strng,_pattern)
local t = {}
for val in string.gmatch(_strng,_pattern) do
table.insert(t,val)
end
return t
end
local r = {}
t1 = getStrng(s1,pattern)
t2 = getStrng(s2,pattern)
for k = 1,#t1 do
if (t1[k] == t2[k]) then
r[t1[k + 1]] = t2[k + 1]
end
endhttps://stackoverflow.com/questions/28793886
复制相似问题