Saucy
Saucy

Reputation: 175

How to match single digits and digits separated by a hyphen with string.match?

I'm trying to match for two types of strings. I wish to capture both of them, but I can only capture one so far.

function roll(input)
  min, high = string.match(input, '(%d+)-(%d+)');

  return min, high;
end

The input strings are: 10-100 and 10

My first string returns as expected but my second (the single digit) returns nil/match not found.

I wish to check if the second part of the pattern is included or not, as it should always print out my min variable.

Upvotes: 1

Views: 163

Answers (1)

Oliver
Oliver

Reputation: 29483

Easiest is to do it separately:

function roll(input)
  local min,high = string.match(input, '(%d+)-(%d+)')
  if min == nil then 
    min = string.match(input, '(%d+)')
  end
  return min, high
end

print(roll '10')
print(roll '10-100')

Upvotes: 2

Related Questions