Skip to content

Instantly share code, notes, and snippets.

@tcr
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcr/f54a2b41b882d243215f to your computer and use it in GitHub Desktop.
Save tcr/f54a2b41b882d243215f to your computer and use it in GitHub Desktop.
-- match regex /a*b/
print('/a*b/')
-- Lua wrapper to extract a character from a string
-- at the indexth position (starting from 0)
-- This is just a helper since Lua is 1-indexed which
-- is insane. You can just copy this out.
function charat (str, index)
return string.sub(str, index + 1, index + 1)
end
-- our generated function that corresponds to our input regex. return true if a string matches
function doesmatch (str)
local index = 0
-- a*
while index < #str do
if charat(str, index) == 'a' then
index = index + 1
else
break
end
end
-- b
if charat(str, index) ~= 'b' then
return false
else
index = index + 1
end
-- make sure we've matched the whole string by comparing index with length of string
if index < #str then
return false
end
return true
end
print(doesmatch('aaaaaab'), 'should equal', true)
print(doesmatch('ab'), 'should equal', true)
print(doesmatch('b'), 'should equal', true)
print(doesmatch('bb'), 'should equal', false)
-- match regex /(b|c*d)/
print('/(b|c*d)e/')
-- Lua wrapper to extract a character from a string
-- at the indexth position (starting from 0)
-- This is just a helper since Lua is 1-indexed which
-- is insane. You can just copy this out.
function charat (str, index)
return string.sub(str, index + 1, index + 1)
end
-- our generated function that corresponds to our input regex. return true if a string matches
function doesmatch (str)
local index = 0
-- (
local subexpr = false
local subexprindex = index
-- b
if not subexpr then
subexpr = true -- assume match until proven false
if charat(str, subexprindex) == 'b' then
subexprindex = subexprindex + 1
else
subexpr = false
end
end
-- c*d
if not subexpr then
subexpr = true -- assume match until proven false
-- c*
while subexprindex < #str do
if charat(str, subexprindex) == 'c' then
subexprindex = subexprindex + 1
else
break
end
end
-- d
if charat(str, subexprindex) ~= 'd' then
subexpr = false
-- this would be "return false" on top-level
else
subexprindex = subexprindex + 1
end
end
-- )
if not subexpr then
return false
else
-- update "top-level" index with our index in the subexpression
index = subexprindex
end
-- e
if charat(str, index) ~= 'e' then
return false
else
index = index + 1
end
-- make sure we've matched the whole string by comparing index with length of string
if index < #str then
return false
end
return true
end
print(doesmatch('be'), 'should equal', true)
print(doesmatch('de'), 'should equal', true)
print(doesmatch('cccd'), 'should equal', false)
print(doesmatch('bbbde'), 'should equal', false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment