4

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?

2 Answers 2

6

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.

-1

In this case it should just be used for grouping things, which doesn't matter much either way here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.