Murga-Projects Forums

Full Version: match one of three possible substrings?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
It doesn't look like this is possible, but i'm often wrong =o)
In Bash you can use *.{png,jpg,gif} to match any of 3 possible filename extensions.
Can this be done in Lua?
What I have right now works, but it seems terribly redundant:

Code:
for i=1,table.getn(allfiles) do
if string.find(allfiles[i],"%.png$") or string.find(allfiles[i],"%.jpg$") or string.find(allfiles[i],"%.gif$") then
some_commands
end
end


Thanks for reading.

mikshaw Wrote:

Code:
if string.find(allfiles[i],"%.png$") or string.find(allfiles[i],"%.jpg$") or string.find(allfiles[i],"%.gif$") then


The trick is to use regular expressions. Unfortunately, lua doesn't implement the PCRE ones, only a simplified version of it. You can find information about this in this Patterns Tutorial or in this lua cheat sheet (pdf).

You can try something like this:

Code:
extension = string.find(allfiles[i],"(%.[pjg][npi][gf]$)")
if extension = ".png" or extension = ".jpg" or extension = ".gif" then
  ......
end


The first line will capture the extension part. [pjg] means a letter that matches any on of p, j, or g.

You can also check out string.gmatch and string.match if you want to run your search on the full list rather than on element x of the list.

Thanks for the pointers.
It still seems to be overkill to first match all similar extensions, including ppf, ppg, pnf, png, pig, pif, jng, jif, ...
...and then check for the three desired extensions. The same result could be obtained by grabbing the filename extension regardless of what it is, if you are then simply going to compare it with ".png", ".jpg" and ".gif"

I'm guessing this is not going to be as straightforward as using "typical" regular expressions, but i still get the feeling that it could be made simpler than it is.

I'll look at match/gmatch to see what can be done there.
I made some apparent progress using a nested loop, although I'm not sure that it is truly progress in the sense of processor/memory usage

Code:
allfiles=murgaLua.readDirectory(realdatadir)
imgtype = { "png", "jpg", "gif" }
for i=1,table.getn(allfiles) do
for t=1,table.getn(imgtype) do
if string.find(allfiles[i],"%."..imgtype[t].."$") then
print('<img src="'..datadir..title..'/'..allfiles[i]..'" alt="'..allfiles[i]..'"/>')
end
end
end


for comparison, here's the same thing done with multiple string searches:

Code:
allfiles=murgaLua.readDirectory(realdatadir)
for i=1,table.getn(allfiles) do
if string.find(allfiles[i],"%.png$") or string.find(allfiles[i],"%.jpg$") or string.find(allfiles[i],"%.gif$") then
print('<img src="'..datadir..title..'/'..allfiles[i]..'" alt="'..allfiles[i]..'"/>')
end
end

Reference URL's