lua-users home
lua-l archive

Re: A Lua pattern question about optional patterns

[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')
foonil
> = double_match('foo;1')
foo1
> = double_match('foo;444')
foo444
> = 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

AltStyle によって変換されたページ (->オリジナル) /