Reputation: 6998
I have a table of strings:
self.rooms = { "n", "s", "e", "w", "nw", "ns", "ne", "sw", "se", "ew", "nsw", "nse", "swe", "nwe", "nsew" }
I then get a string that will have any combination of these and I want to find in the above table that contains the letters in any order.
So if I have a string "es" then I should get returned:
"se", "nse", "nsew", "swe" because they all have the letter 'e' AND 's' in them.
Is there any match that can do this?
Upvotes: 1
Views: 51
Reputation: 72312
Try this:
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
Upvotes: 2
Reputation: 2205
I tried to find a solution for any combination of letters, subject to the mandatory presence of each in the sample:
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
print:
se
nse
swe
nsew
Upvotes: 1