这个Lua模式中的括号有什么用? [英] what are the use of parentheses in this Lua pattern?

查看:404
本文介绍了这个Lua模式中的括号有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本字符串为:IP: 192.168.0.1

将该字符串传递给string.gmatch函数(以下模式除外)将返回以下结果:

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

模式:IP: (%d+.%d+.%d+.%d+) -> 192.168.0.1

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

模式:IP: %d+.%d+.%d+.%d+ -> IP:192.168.0.1

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

我的问题是,Lua模式匹配引擎的这些括号的含义是什么? 为什么通过在第一个模式中使用括号来省略IP:字符串,而在第二个模式中不使用字符串?

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?

推荐答案

括号内的任何内容都是捕获组match()gmatch()捕获并返回输入字符串中与括号中的模式部分匹配的任何部分.如果该模式中没有捕获组,则返回整个字符串.

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

在指定关联的捕获组之后的任何时候,可以使用%1%2等访问捕获的值:

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

这在string.gsub()的第三个参数中最常见,但是可以在任何模式匹配功能中使用.

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

这篇关于这个Lua模式中的括号有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆