what are the use of parentheses in this Lua pattern?

血红的双手。 提交于 2019-12-05 19:53:04

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!