[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua idiom for RE-style alternation?
- From: David Manura <dm.lua@...>
- Date: Wed, 6 Jan 2010 20:32:33 -0500
On Wed, Jan 6, 2010 at 3:33 PM, duck wrote:
> What is "Lua idiom" -- using the regular string library, not lpeg or any
> of the RE add-ons -- when doing string matching with alternative
> strings in it. For example, something like this:
> "eat (green|yellow)? (bananas|apples) daily"
There's xpattern [1]. Example:
local XP = require "xpattern"
XP.debug = true -- prints Lua function code
local P = XP.P
local pat = P'eat ' * (P'green' + P'yellow')^-1 * P' '
* (P'bananas' + P'apples') * ' daily'
local m = pat:compile()
print('1:', m('eat blue apples daily'))
print('2:', m('eat green bananas daily'))
Output:
DEBUG:
local match = ...
return function(s,pos)
for pos1=(pos or 1),#s do
local pos2
pos2 = match(s, "^eat ()", pos1)
if pos2 then
do
local pos3=pos2
local pos4 = pos3
pos4 = match(s, "^green()", pos3)
if not pos4 then
pos4 = match(s, "^yellow()", pos3)
end
pos3 = pos4
if pos3 then
pos2=pos3
else
pos2=pos2
end
end
end
if pos2 then
pos2 = match(s, "^ ()", pos2)
end
if pos2 then
local pos3 = pos2
pos3 = match(s, "^bananas()", pos2)
if not pos3 then
pos3 = match(s, "^apples()", pos2)
end
pos2 = pos3
end
if pos2 then
pos2 = match(s, "^ daily()", pos2)
end
if pos2 then return s:sub(pos1,pos2-1) end
end
end
1:
2: eat green bananas daily
[1] http://lua-users.org/wiki/ExPattern