[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Problems with an lpeg grammar
- From: Glenn McAllister <glenn@...>
- Date: Thu, 27 Mar 2008 19:41:56 -0400
I'm having trouble figuring out how to create a grammar that lets me
replace escape sequences in a string, when the unescaped version of the
string triggers another pattern. I also need to state up front that I'm
new to PEGs and I'm probably missing something fairly straightforward.
I'm happy to RTFM, but the main LPeg web page isn't shedding much light
for me atm.
Lets start with the relevant PEG, which hopefully is correct in the
first place:
Template <- Chunk+ End
Chunk <- Literal / Action / Newline
Newline <- '\n' / '\r'
Action <- ActionStart (!ActionEnd .)+ ActionEnd
ActionStart <- !'\\' '$'
ActionEnd <- '$'
Literal <- ((!Action / !Newline) .)+
End <- !.
Basically I want the following:
1) "text1 $action1$ text2" -> { 'text1', 'action1', 'text2' }
2) "text1\ntext2\ntext3" -> { 'text1', 'text2', 'text3' }
3) "text2 tex\$t2" -> { 'text1', 'tex$t2' }
Here's what I have so far, which will do 1) and 2), but obviously not 3):
local grammar = {
"Template",
Template = lpeg.Ct(Chunk^1) * -1,
Chunk = Literal + Action + Newline,
Newline = lpeg.C(lpeg.S'\n\r'),
ActionStart = lpeg.P'$' - lpeg.P'\\',
ActionEnd = lpeg.P'$',
Action = ActionStart * lpeg.C((1 - ActionEnd)^1) * ActionEnd,
Literal = lpeg.C((1 - (ActionStart + Newline))^1)
}
It basically comes down to me not knowing how to do the substitution in
the Literal definition. I looked as the CSV example, but it wasn't
shedding a lot of light for me.
Thanks,
--
Glenn McAllister <glenn@somanetworks.com> +1 416 348 1594
SOMA Networks, Inc. http://www.somanetworks.com/ +1 416 977 1414
Asking a writer what he thinks about criticism is like asking a
lamppost what it feels about dogs.
- John Osborne