LPEG
LPeg is a new pattern-matching library for Lua, based on Parsing Expression Grammars (PEGs). This text is a reference manual for the library.
Usage
> lpeg.P("hello"):match("hello world") -- Matches string literally, you can also pass a number (n) and it will match the n chars
6
> lpeg.S("aeiou"):match("ello world") -- Set, matches anything in the set
2
> lpeg.R("AZ", "az"):match("A") -- Range, matches chars from A to Z and a to z (accepts multiple ranges)
2
> lpeg.R("AZ") + lpeg.P("117") -- + is the union (OR) of the two pattern, lpeg is possessive, meaning it won't backtrack to try to find matches/find bigger matches, so it's ordered
> lpeg.R("AZ") * lpeg.P("117") -- * works like AND (concat)
> lpeg.R("AZ")^0 -- means zero or more
> lpeg.R("AZ")^-1 -- means zero or one
> (lpeg.P("a")^0 * lpeg.C(lpeg.P(1))):match("aaabc") -- lpeg.C captures the pattern (matches return all captured values)
b
-- you can also just use lpeg.C(1) <-- anything that is not an lpeg is going to be transformed in lpeg object by using lpeg.P
> lpeg.Cp() -- <--- captures current position
> - lpeg.P("a") -- matches anything that is not a
> lpeg.P("do") * -lpeg.P(1) --matches only when do is followed by end of string (e.g. it won't match against dont)
> lpeg.P(-1) == -lpeg.P(1)