【问题标题】:problems with Lua match to find a patternLua 匹配查找模式的问题
【发布时间】:2015-03-01 13:07:07
【问题描述】:

我正在努力解决这个问题:

给定 2 个字符串:

s1 = '/foo/:bar/oof/:rab'
s2 = '/foo/lua/oof/rocks'

我想提供以下信息:

  1. 如果它们匹配(上面这两个应该匹配,s2 遵循 s1 中描述的模式)。

  2. 一个表,其中包含s2 的值以及s1 中的相应名称。在这种情况下,我们将拥有:{ bar = "lua", rab = "rocks" }

我认为这个算法可以解决它,但我不知道如何实现它(可能使用 gmatch):

  1. 将占位符 : 索引存储为表的 KEYS,并且相应的 VALUES 是这些占位符的名称。

    s1 为例:

    local aux1 = { "6" = "bar", "15" = "rab" }
    
  2. aux1的键为索引,提取s2的值 进入另一个表:

    local aux2 = {"6" = "lua", "15" = "rocks"}
    
  3. 最后将它们两个合并到一个表中(这个很简单:P)

    { bar = "lua", rab = "rocks" }
    

【问题讨论】:

  • 在第 2 步中,您使用 s1 中的索引来查找 s2 中的点,这仅适用于 ":bar" 与 "lua" 的长度相同,会一直如此吗?跨度>
  • 实际上这个逻辑有一个缺陷,我正在研究基于在“/”上拆分字符串的解决方案

标签: lua lua-patterns


【解决方案1】:

可能是这样的:

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

【讨论】:

    【解决方案2】:

    另一种解决方案可能是:

    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
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-03
      • 2011-06-28
      • 2013-01-19
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      相关资源
      最近更新 更多