开发者

string.match and regex in Lua, is it possible?

I'm currently working on a script gathering information from a website. I'm wondering if string.matc开发者_JAVA百科h would be able to accept regex pattern matching, such as the following:

string.match(page, "(?:(Phrase One|Phrase Two|Phrase Three|...))")

The problem is, I don't know if it can be done, but I'm willing to try any solutions. Thanks!


You can use the Lrexlib if you need full blown regular expressions.


What you could do is to define a function which takes your patterns as a table and then returns a table of matches, or if you only need to know if the text is contained in the page then following would work.

    function FindAny(strContent,tblPatterns)
    bReturn = false
    for i,strPattern in ipairs(tblPatterns) do
        if (string.find(strContent,strPattern) ~= nil) then
            bReturn = true
            break
        end
    end
    return bReturn
end
if FindAny('pattern 4',{'pattern 1','pattern 2','pattern 3','pattern 4'}) then
    print('Pattern Found')
end


Lua doesn't come with regular expressions built-in but there are a couple add-on modules for that. Here's one: http://www.inf.puc-rio.br/~roberto/lpeg/re.html

That said, gmatch() can be used for the problem you describe, it's just a different syntax than regular expressions. Here are explanations:

http://lua-users.org/wiki/StringLibraryTutorial

http://www.wowpedia.org/Pattern_matching


As far as http://lua-users.org/wiki/StringLibraryTutorial indicates in the gsub method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜