regexlualpeg

Matching an optional number in a Lua pattern


I'm parsing the output from the diff3 command and some lines look like this:

1:1,2c
2:0a

I am interested in the numbers in the middle. Its either a single number or a pair of numbers separated by commas. With regexes I can capture them both like this:

/^\d+:(\d+)(?:,(\d+))?[ac]$/

What is the simplest equivalent in Lua? I can't pass a direct translation of that regex to string.match because of the optional second number.


Solution

  • Using lua patterns, you could use the following:

    ^%d+:(%d+),?(%d*)[ac]$
    

    Example:

    local n,m = string.match("1:2,3c", "^%d+:(%d+),?(%d*)[ac]$")
    print(n,m) --> 2    3
    
    local n,m = string.match("2:0a", "^%d+:(%d+),?(%d*)[ac]$")
    print(n,m) --> 0