代码之家  ›  专栏  ›  技术社区  ›  user441521

字符串中的每个字符在另一个字符串中以任意顺序存在

lua
  •  1
  • user441521  · 技术社区  · 8 年前

    我有一张字符串表:

    self.rooms = { "n", "s", "e", "w", "nw", "ns", "ne", "sw", "se", "ew", "nsw", "nse", "swe", "nwe", "nsew" }
    

    然后我得到一个字符串,该字符串将包含这些字符的任意组合,我想在上表中找到包含字母的任意顺序。

    因此,如果我有一个字符串“es”,那么我应该得到返回:

    “se”、“nse”、“nsew”、“swe”,因为它们都有字母“e”和“s”。

    有什么匹配可以做到这一点吗?

    2 回复  |  直到 8 年前
        1
  •  2
  •   lhf    8 年前

    尝试以下操作:

    rooms = { "n", "s", "e", "w", "nw", "ns", "ne", "sw", "se", "ew", "nsw", "nse", "swe", "nwe", "nsew" }
    
    function normalize(s)
        local t=""
        if s:match("n") then t=t.."n"..".*" end
        if s:match("s") then t=t.."s"..".*" end
        if s:match("e") then t=t.."e"..".*" end
        if s:match("w") then t=t.."w" end
        return t
    end
    
    p = normalize("es")
    
    for i,v in ipairs(rooms) do
        if v:match(p) then print(v) end
    end
    
        2
  •  1
  •   Mike V.    8 年前

    我试图找到任何字母组合的解决方案,但每个字母都必须出现在样本中:

    local rooms = { "n", "s", "e", "w", "nw", "ns", "ne", "sw", "se", "ew", "nsw", "nse", "swe", "nwe", "nsew" }
    
    function MyFind (inp, str)
          if str=="" then return false end
          local found=true
          string.gsub(str, '.', function (c)  -- this code can be replaced with a 'for' loop
                if inp:find(c) and found then found=true else  found=false end
              end)
          return found ,inp  
     end
    
    local chars = "se"    -- 1,2,3.. or more letters
    for _,v in pairs(rooms) do
          a,b = MyFind (v, chars)
          if a then print (b) end
    end
    

    打印:

    se
    nse
    swe
    nsew