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.

有帮助吗?

解决方案

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')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top