lua-users home
lua-l archive

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


> On Jan 25, 2018, at 11:01 PM, Sean Conner <sean@conman.org> wrote:
> 
> It was thus said that the Great albertmcchan once stated:
>> 
>>> On Jan 25, 2018, at 8:03 PM, Sean Conner <sean@conman.org> wrote:
>>> 
>>> If you are looking for a final "and" (which ends the input), then this
>>> works:
>>> 
>>>   last_and = P"and" * P(-1)
>>>   char     = R("\0\96","b\255")^1
>>>                + -last_and * P"a"
>>>   pat      = C((char)^0) * last_and
>>> 
>>>   print(pat:match(string.rep("this and that land",400) .. "and"))
>> 
>> your example also shows usefulness of undo lpeg.U (if exist):
>> 
>> pat = C( P(1)^3 * U(3) * #P'and' )
> 
>  Even if lpeg.U() existed, I don't think this would do what you expect

Sorry for the mis-understanding.
I was referring to YOUR example, a final "and" (which ends the input).

The natural way of matching is to move to position -3, then check for 'and'
If I use lua string library, i would do this:

function string_match_and_at_endofstring(s)
   if string.sub(s, -3) ~= 'and' then return nil end
   return string.sub(s, 1, -4)
end

Above code, literally translate to lpeg (if #s is available)

function lpeg_match_and_at_endofstring(s)
   local pat = C(P(#s - 3) * #P'and')
   return lpeg.match(pat, s)
end

Without #s and if U exist then pat = C(P(1)^3 * U(3) * #P'and')