[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Can someone convert this POSIX regex to a Lua regex?
 
- From: steve donovan <steve.j.donovan@...>
 
- Date: Wed, 21 Oct 2009 08:34:13 +0200
 
On Tue, Oct 20, 2009 at 10:13 PM, Duncan Cross <duncan.cross@gmail.com> wrote:
> However, if you'd like to see what a "pure-Lua" solution would look
> like, here is one. It's not exactly identical, because unlike your
> regex it will fail to match things like 'pi()' and 'pipi', but I can't
> imagine that was intentional anyway.
That's the thing about regexes; a reasonably complicated one takes a
whole mailing list thread to untangle ;)
Another approach is to use a lexical analylizer:
require 'lexer'
local names = {
-- functions
 ceil=1, abs=1, floor=1, mod=1, exp=1, log=1, pow=1, sqrt=1,
 acos=1, asin=1, atan=1, cos=1, sin=1, tan=1, deg=1, rad=1,
 random=1,
-- constants
 pi = 0
}
function match(str)
  local res = {}
   local tok = lexer.c(str)
   local t,val = tok()
   while t do
     if t == 'iden' and names[val] then
       if names[val] == 0 then table.insert(res,val) -- a constant!
      else -- a function; is it followed by parens?
        t,val = tok()
        if t == '(' then return table.insert(res,val..'(') end
     end
   end
   t,val = tok()
  end
 return res
end
This has the advantage of not being confused by things like /* sin(x) */
steve d.