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

我有一个字符串表:

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

然后我得到一个字符串,它将具有任何这些的组合,并且我希望在上面的表中找到包含任意顺序的字母的表。

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

"se","nse","nsew","swe",因为它们都包含字母'e'和's'。

是否有任何匹配可以做到这一点?

点赞
用户107090
用户107090

尝试一下:

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
2018-03-24 19:25:59
用户7504558
用户7504558

我尝试寻找任意字母组合的解决方案,同时保证样本中的每个字母必须存在:

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)  -- 这段代码可以用 'for' 循环替代
            if inp:find(c) and found then found=true else  found=false end
          end)
      return found ,inp
 end

local chars = "se"    -- 一个、两个、三个或更多字母
for _,v in pairs(rooms) do
      a,b = MyFind (v, chars)
      if a then print (b) end
end

输出:

se
nse
swe
nsew
2018-03-25 07:04:38