Search code examples
lualua-patterns

what are the use of parentheses in this Lua pattern?


base string is: IP: 192.168.0.1

Passing that string to string.gmatch function(besides below patterns) will return the following results:

pattern: IP: (%d+.%d+.%d+.%d+) -->192.168.0.1

pattern: IP: %d+.%d+.%d+.%d+ -->IP: 192.168.0.1

My question is that what are the meaning of those parentheses to the Lua pattern matching engine? Why by using the parentheses in the first pattern, the IP: string omitted but in the second pattern no?


Solution

  • Anything inside parentheses is a capture group; any part of the input string matched by the part of the pattern in parentheses is captured and returned by match() and gmatch(). If there are no capture groups in the pattern, the entire string is returned.

    local x, y, z = ("123456"):match("(%d)%d(%d)%d(%d)%d")
    print(x, y, z)
    -- 1, 3, 5
    

    At any point after the associated capture group is specified, %1, %2 etc. may be used to access the captured value:

    local x, y = ("123123123"):match("(%d%d%d)%1(%1)")
    print(x, y)
    -- 123, 123
    

    This is most often seen in the third parameter of string.gsub(), but may be used in any of the pattern matching functions.