匹配Lua模式中的可选数字

时间:2014-09-17 03:31:39

标签: regex lua lpeg

我正在解析diff3命令的输出,有些行看起来像这样:

1:1,2c
2:0a

我对中间的数字很感兴趣。它是由逗号分隔的单个数字或一对数字。使用正则表达式,我可以像这样捕获它们:

/^\d+:(\d+)(?:,(\d+))?[ac]$/

Lua中最简单的等价物是什么?由于可选的第二个数字,我无法将该正则表达式直接转换为string.match。

2 个答案:

答案 0 :(得分:4)

使用lua模式,您可以使用以下内容:

^%d+:(%d+),?(%d*)[ac]$

示例:

local n,m = string.match("1:2,3c", "^%d+:(%d+),?(%d*)[ac]$")
print(n,m) --> 2    3

local n,m = string.match("2:0a", "^%d+:(%d+),?(%d*)[ac]$")
print(n,m) --> 0

答案 1 :(得分:2)

您也可以使用lua模式实现它:

local num = str:match '^%d+:(%d+),%d+[ac]$' or str:match '^%d+:(%d+)[ac]$'
相关问题