lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Hello LPeg experts :)  ,

I am trying to replicate some of PCRE patterns in LPeg as an educational exercise ...

First, this PCRE pattern:

([a-z]+) and (?1)

This matches something like "fish and chips" or "fish and fish" as the (?1) is a "subroutine call" to repeat the earlier pattern #1.

This seems to be easy in LPeg, as it lets you break patterns down, like this:

require "lpeg"

word = lpeg.C (lpeg.R ("az")^1)
phrase = word * " and " * word

print (lpeg.match (phrase, "fish and chips"))  --> fish chips
print (lpeg.match (phrase, "fish and fish"))   --> fish fish


However the next case is a bit harder. In PCRE:

([a-z]+) and \1

This matches "fish and fish" but NOT "fish and chips" because the \1 means "match the exact same thing as pattern 1" (not the same type of thing).

The best I could do in LPeg is this:

require "lpeg"

word = lpeg.C (lpeg.R ("az")^1)
phrase = word *
         " and " *
         lpeg.Cmt (word * lpeg.Cb (2),
                   function (s, i, a, b) return a == b end)

print (lpeg.match (phrase, "fish and chips"))  --> nil
print (lpeg.match (phrase, "fish and fish"))   --> fish

Is this the best way of achieving this?


On the web page you mention that the lpeg.Cb is an experimental feature. What is its current status? The example at the bottom ("The next example mathes Lua long strings:") uses it, so presumably you are reasonably keen on it.

By the way, there is a typo there (the word "mathes").


LPeg is current version 0.8.1 - is there any projected release date for version 1? Presumably this will be a stable version with its features frozen.


The makefile that ships with LPeg 0.8.1 mentions one of Roberto's directories explicitly:

LUADIR = /home/roberto/prj/sw/oldlua/lua-5.1.2/src

Perhaps that should be changed in future. I tried to write to Roberto privately about that, but unfortunately the anti-spam software at his email address rejected my email for some reason. Apparently my IP address in on some SORBS list, however my Internet provider is Telstra BigPond, the largest provider of Internet connectivity in Australia, and the operator of the telephone network.

Best regards,

- Nick