Created
October 10, 2015 17:40
-
-
Save mjohnson9/9d29f644d365807f351f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ffi = require("ffi") | |
local pcre = ffi.load("pcre") | |
ffi.cdef([[ | |
typedef struct real_pcre pcre; | |
typedef struct pcre_extra pcre_extra; | |
typedef const char * PCRE_SPTR; | |
static const int PCRE_STUDY_JIT_COMPILE = 0x0001; | |
pcre *pcre_compile(const char *, int, const char **, int *, | |
const unsigned char *); | |
pcre_extra *pcre_study(const pcre *, int, const char **); | |
int pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR, | |
int, int, int, int *, int); | |
void pcre_free_study(pcre_extra *); | |
void (*pcre_free)(void *); | |
]]) | |
local function pcre_compile(pattern, options) | |
local err = ffi.new("const char *[1]") | |
local erroffset = ffi.new("int[1]") | |
local res = pcre.pcre_compile(pattern, options, err, erroffset, nil) | |
if err[0] ~= nil then | |
error("error in regular expression at character "..erroffset..": "..ffi.string(err[0])) | |
end | |
ffi.gc(res, pcre.pcre_free) | |
return res | |
end | |
local function pcre_study(regex) | |
local err = ffi.new("const char *[1]") | |
local res = pcre.pcre_study(regex, pcre.PCRE_STUDY_JIT_COMPILE, err) | |
if err[0] ~= nil then | |
error("error studying regular expression: "..ffi.string(err[0])) | |
end | |
ffi.gc(res, pcre.pcre_free_study) | |
return res | |
end | |
local function pcre_exec(regex, regex_extra, str) | |
local rc = pcre.pcre_exec(regex, regex_extra, str, #str, 0, 0, nil, 0) | |
return rc | |
end | |
local Regex = {} | |
Regex.__index = Regex | |
function compile(pattern) | |
local r = setmetatable({}, Regex) | |
r:_init(pattern) | |
return r | |
end | |
function Regex:_init(pattern) | |
self.pattern = pattern | |
self._pcre = pcre_compile(pattern, 0) | |
self._pcre_extra = pcre_study(self._pcre) | |
end | |
function Regex:match(str) | |
return pcre_exec(self._pcre, self._pcre_extra, str) | |
end | |
return { | |
compile = compile | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment