2

I'm parsing the output from the diff3 command and some lines look like this:

1:1,2c
2:0a

I am interested in the numbers in the middle. Its either a single number or a pair of numbers separated by commas. With regexes I can capture them both like this:

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

What is the simplest equivalent in Lua? I can't pass a direct translation of that regex to string.match because of the optional second number.

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • The comma acts as a separator between the first number (which is always present) and the second number (which is optional) – hugomg Sep 17 '14 at 03:54
  • @AvinashRaj: This question is for Lua, which doesnt have a standard regexes in the stdlib. – hugomg Sep 17 '14 at 03:56

2 Answers2

4

Using lua patterns, you could use the following:

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

Example:

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
hwnd
  • 69,796
  • 4
  • 95
  • 132
2

You can achieve it using lua patterns too:

local num = str:match '^%d+:(%d+),%d+[ac]$' or str:match '^%d+:(%d+)[ac]$'
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • This one-liner doesn't work if I need to capture both numbers as in `local n,m = ...`. Copying and pasting the pattern is a simple thing that went right over my head though. – hugomg Sep 17 '14 at 03:55
  • @hugomg You can set the second number group to be `%d-` (or `%d*`) to match `0` occurrences as well. – hjpotter92 Sep 17 '14 at 04:08