lua-users home
lua-l archive

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


> On 9/16/07, gary ng <garyng2000@yahoo.com> wrote:
> > What would be the equivalent of pattern{x,y} in regex,
> > i.e. pattern can occur between x and y times ?
> 
> First attempt:
> 
> function lpeg.minmax(patt,min,max)
>    return #(lpeg.P(patt)^min) * lpeg.P(patt)^-max
> end

Second attempt: (It is much more work, but the result is more efficient,
as it does not read the patterns twice.)

local function mult (p, n)
  local np = m.P(true)
  while n >= 1 do
    if n%2 >= 1 then np = np * p end
    p = p * p
    n = n/2
  end
  return np
end

local function minmax (p, min, max)
  if max == true then return p^min
  else
    max = (max == false) and min or max
    if max < min then return m.P(false) end
    local r = mult(p, min)
    if max > min then r = r * p^(min - max) end
    return r
  end
end

(max == true means no maximum; max == false means exactly min repetitions)

(The next version of 're' will support this syntax.)

-- Roberto