hugomg
hugomg

Reputation: 69934

Matching an optional number in a Lua pattern

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.

Upvotes: 2

Views: 2060

Answers (2)

hwnd
hwnd

Reputation: 70722

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

Upvotes: 4

hjpotter92
hjpotter92

Reputation: 80639

You can achieve it using lua patterns too:

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

Upvotes: 2

Related Questions