1

Consider the following lpeg pattern

pat = lpeg.C((lpeg.P " ")^0 * lpeg.C(lpeg.R "az") * lpeg.P ".")
lpeg.match(lpeg.Ct(pat), "    a.")

I would like to capture both the full substring and the letter only as two different named patterns, but I have some difficulties figuring out how this can be done. A named capture doesn't seem to survive an outer capture, e.g.

pat = lpeg.C((lpeg.P " ")^0 * lpeg.Cg(lpeg.C(lpeg.R "az"), "letter") * lpeg.P ".")
lpeg.match(lpeg.Ct(pat), "    a.")

only produces {" a."}, without letter. At the same time I see no obvious way to unpack the two captured items into two separate groups without jumping though some very weird hoops (like capturing them into a named table and then using back captures to extract the individual items...

MrMobster
  • 1,851
  • 16
  • 25
  • I don't know if this is also a weird hoop: `pat = lpeg.C((lpeg.P " ")^0 * lpeg.C(lpeg.R "az", "letter") * lpeg.P ".") / function(whole, letter) return { whole = whole, letter = letter } end`. – Sewbacca Nov 26 '22 at 03:21
  • Unfortunately it doesn't seem to do what I need since it captures one table rather than two named captures. I need to be able to refer to the the captured values using Cb etc. – MrMobster Nov 27 '22 at 15:59
  • It's not possible to nest named captures in LPeg. Based on my personal experience, LPeg's back capture (`Cb`) can only be used for some simple scenarios. – Brynne Taylor Nov 30 '22 at 04:57
  • Why do you need to make a back reference? If you want to build complexer patterns, you could rebuild the same string if you capture what came before and what comes after and use three `Cb`. – Sewbacca Dec 03 '22 at 02:25

0 Answers0