what are the use of parentheses in this Lua pattern?

巧了我就是萌 提交于 2019-12-07 17:03:41

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/11693730/what-are-the-use-of-parentheses-in-this-lua-pattern

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