lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Sep 10, 2019, at 7:04 AM, Peter W A Wood <peterwawood@gmail.com> wrote:

I also came up with a two-step method but wasn’t sure if it was really applicable in the actual use case. My solution does not seem very elegant but handles Sean’s five examples properly:

> function double_match (s)
>> local text = s:match('^(%a+)$')
>>   if text then
>>     return text, nil
>>   else
>>     return s:match('^(%a+);(%d+)')
>>   end
>> end
> = double_match('foo')
foo nil
> = double_match('foo;1')
foo 1
> = double_match('foo;444')
foo 444
> = double_match('foo;')
nil
> = double_match('foo23')
nil

Peter

This version avoided "double matching", perhaps slightly more efficient:

function match2(s)
    if #s == 0 then return end
    local i = string.find(s, "%A")
    if i == nil then return s, nil end
    i = string.find(s, "^;%d+$", i)
    if i then return s:sub(1,i-1), s:sub(i+1) end
end