Search code examples
regexlualua-patterns

Something Strange happend in lua regexp,What's wrong with my script?


Lua's regexp isn't compatible with Posix RegExp. For example, %d means \d which represents Number:0 to 9. And '%' is for escaping.

I want to match something like "180*180,512*512" which describe image size sequencies. In Posix mode,This regexp does work for me: ^(\d+\*\d+)(,\d+\*\d+)*$, And I changed this to Lua regexp mode: ^(%d+%*%d+)(,%d+%*%d+)*$, but it doesn't work. Here is my code

#!/usr/local/bin/lua

source = '96*96,180*180';
format = "^(%d+%*%d+)(,%d+%*%d+)*$";


if (not string.find(source, format)) then
    print 'wrong!'
else
    print 'ok!'
end

Solution

  • Lua does not have regex. It has its own patterns, as described in PiL.

    For your particular case, you can simple replace the regex:

    ^(\d+\*\d+)(,\d+\*\d+)*$
    

    to the following pattern:

    ^(%d+%*%d+)(,%d+%*%d+)$
    

    Note that I removed the * after your second match-group, because Lua does not support it. You'll have to resort to using gmatch for capturing multiple groups:

    local tMatches = {}
    for sSize in str:gmatch "(%d+%*%d+)" do
        table.insert( tMatches, sSize )
    end