lua-users home
lua-l archive

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




2011/6/21 Daurnimator <quae@daurnimator.com>
On 21 June 2011 17:37, Dirk Laurie <dpl@sun.ac.za> wrote:
> I am tempted to ask (but won't) why there isn't any lpeg.L(lpat) that
> returns an lpeg pattern that matches the same strings, and returns
> the same captures, that the Lua pattern lpat would.
>
> Instead, I'm asking whether a question similar to this has burgeoned
> in the brain of a list member for long enough that some work in this
> direction has been done.
>
> Dirk
>
>

I started working on it after I saw this post:
local lpeg = require "lpeg"
local P , R , S , V = lpeg.P , lpeg.R , lpeg.S , lpeg.V
local C , Carg , Cb , Cc , Cf , Cg , Ct , Cmt = lpeg.C , lpeg.Carg ,
lpeg.Cb , lpeg.Cc , lpeg.Cf , lpeg.Cg , lpeg.Ct , lpeg.Cmt
local locale = lpeg.locale ( )

local patt_or = function ( patt1 , patt2 )
       return patt1 + patt2
end
local patt_then = function ( patt1 , patt2 )
       return patt1 * patt2
end

local makerange = function ( from , to )
       return R(from .. to)
end

local classes = setmetatable ( {
       a = locale.alpha ;
       c = locale.cntrl ;
       d = locale.digit ;
       l = locale.lower ;
       p = locale.punct ;
       s = locale.space ;
       u = locale.upper ;
       w = locale.alnum ;
       x = locale.xdigit ;
       z = P("\0") ;
} , { __index = function(conv,k)
               error("Invalid class: " .. k)
               return P(k)
       end
} )

local any = P(1)
local eos = P(-1)

local luapattern = P{
       "pattern";
       special = S"^$()%.[]*+-?" ;
       plain = 1-V"special" ;
       range = C(V"plain") * "-" * C(V"plain") / makerange ;
       class = P"."*Cc(any) + P"%"*(locale.alnum/classes+(1-locale.alnum/P))
+ V"plain"/P ;
       set = Cf(P"[" * (P"^"*Cc("complement"))^-1 * (V"range" + V"class")^1
* P"]" , patt_or) ;
       item = V"set" + V"plain"^1 ;
       pattern = Cf( ((-V"item")*any)^-1 * V"item"^0 * (P"$"*Cc(eos))^-1 ,
patt_then );
}
f = luapattern:match("[%a][%d]")
--lpeg.print(f)
print((f):match("dd6"))

I'm interesting with lpeg now :)

A question: How to match the patten between m to n times?
there is something like patt{m,n}?
I have tried patt^m^-n but it just act like patt^0 :(