2012-07-20 98 views
3

我是Lua新手,所以我現在正在學習運算符部分。 有沒有一個通配符可以在Lua中使用字符串?Lua比較運算符(通配符?)

我來自一個PHP的背景,我基本上是試圖實現代碼:

--scan the directory's files 
for file in lfs.dir(doc_path) do 

    --> look for any files ending with .jpg 
    if file is like ".jpg" then 
     --do something if any files ending with .JPG are scanned 
    end 

end 

你會看到我在尋找出JPG文件,而我在一個目錄循環通過的文件。 我習慣於使用百分比符號或星號字符來搜索字符串。 但也許Lua有不同的方式?

另外,我也完全符合陳述猜測:「如果文件是這樣......」

回答

3

你想要的功能string.match(),如果一個字符串相匹配的pattern哪些測試。

這裏是你的榜樣我重新寫(未經測試):

--scan the directory's files 
for file in lfs.dir(doc_path) do 

    --> look for any files ending with .jpg 
    if file:match "%.jpg$" then 
     --do something if any files ending with .JPG are scanned 
    end 

end 

使用方法調用的語法糖file:match "%.jpg%"調用函數string.match的符號,它的作品,因爲所有的字符串值都具有string集作爲其元表由默認。爲了簡化表達式,我也放棄了括號。

該模式在末尾由$錨定到字符串的末尾,並通過引用%來引用文字.。但是,由於模式區分大小寫,因此這只是匹配擴展名全部小寫的文件。

爲了使它不區分大小寫的,最簡單的答案是通過編寫file:lower:match"%.jpg$",測試前的文件名的情況下,其摺疊鏈中的調用matchstring.lower()通話。或者,您可以將模式重寫爲"%.[Jj][Pp][Gg]$"以在任一情況下明確地匹配每個字符。

+0

優秀的解釋。確切地說,我需要閱讀 – coffeemonitor 2012-07-21 00:46:50