2012-07-20 166 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