首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找模式的Lua匹配问题

查找模式的Lua匹配问题
EN

Stack Overflow用户
提问于 2015-03-01 13:07:07
回答 2查看 120关注 0票数 1

我在努力解决这个问题:

给定两个字符串:

代码语言:javascript
复制
s1 = '/foo/:bar/oof/:rab'
s2 = '/foo/lua/oof/rocks'

我想提供以下资料:

  1. 如果它们匹配(这两个应该匹配,s2遵循s1中描述的模式)。
  2. 保存s2值的表,在s1中具有相应的名称。在这种情况下,我们需要:{ bar = "lua", rab = "rocks" }

我认为这个算法解决了这个问题,但是我想不出如何实现它(可能是使用gmatch):

  1. 将占位符:索引存储为表的键,相应的值是这些占位符的名称。 使用s1的示例: 局部aux1 ={ "6“= "bar","15”= "rab“}
  2. aux1的键作为索引,将s2的值提取到另一个表中: 局部aux2 = {"6“= "lua","15”= "rocks"}
  3. 最后将它们合并成一个表(这个表很简单:P) { bar = "lua",rab = "rocks“}
EN

回答 2

Stack Overflow用户

发布于 2015-03-01 15:56:30

可能是这样的:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2016-03-15 22:18:11

另一种解决办法可以是:

代码语言:javascript
复制
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将具有所需的结果

下面的解决方案也会给出同样的结果:

代码语言:javascript
复制
 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
 end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28793886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档