How to match for optional pattern in Lua?

Viewed 79

I am trying to learn how to match for optional pattern in Lua.

local text = '10+'
local start_index, end_index, value = string.find(text, "%d+(%+)")
print(start_index, end_index, value)

Using this as an example, I want + to be optional and still return the index of number when + doesn't exist in that string.

I tried this pattern but it will returns nil, nil, nil

local text = '10+'
local start_index, end_index, value = string.find(text, "%d+(%+)?")
print(start_index, end_index, value)

How can I make + optional correctly in this case?

1 Answers

You need to move the ? into the capture!

local text = '10+'
local start_index, end_index, value = string.find(text, "%d+(%+?)")
print(start_index, end_index, value)
Related