hisham hm

LPEG Cheat Sheet

I once felt that every time I think LPEG is the solution to my problem I spend so much time trying to learn it that I lose focus from the actual problem.

The concept is admirable, though, so for once I decided to struggle through and actually get the job done using it. I learned a few tricks along the way, so I decided I should write them down (because I know I’ll certainly need them in the future).

These assume the one-letter functions are loaded into locals (e.g. P = lpeg.P).

Match a pattern exactly n times

local function X(p,n) return n == 1 and p or p * X(p,n-1) end

Match anything not in a set

(1 - S"abc") -- [^abc]

Match a string converting backslash escape sequences

-- match backslash and capture following char,
-- then convert match to captured char
local escape = (P"\" * C(1)) / "%1"
-- match anything but backslashes and spaces, or escapes
-- turn everything into a capture, replacing inner captures
local pathname = Cs( ( (1 - S"\ ") + escape ) ^ 1 )

Capture a number as a number

local num = (R"09" ^ 1) / tonumber

Add comment

Fill out the form below to add your own comments.

CAPTCHA imageReload imageAudible version of CAPTCHA-image