Can I get some help with a (hopefully) a simple grammar? I haven’t done much with CFGs so I could be totally off base.
I want to find variable expressions in a string.
For example: hello, {{name}}.
This is similar to the Mustache variety of interpolation, but I need to pre-parse it to do something slightly different.
I can recognize the pattern above pretty easily. My problem is having it ignore single brackets.
For example: hello, {{name}}. Please choose {Yes, No}.
The last part is not a double bracket expression and should just be treated like the other uninteresting text.
So, my grammar looks like this (I’ve tried a bunch of other variations, this is the closest I’ve come):
(def p
(insta/parser
"<S> = (block | TXT)*
block = <'{{'> TXT <'}}'>
<TXT> = (OPEN | CLOSE | A | block)*
<OPEN> = !'{' '{'
<CLOSE> = !'}' '}'
<A> = #'[^{}]*'"))
A call (p "x{a}")
yields:
=> Parse error at line 1, column 2:
x{a}
^
Expected one of:
"{{"
"}"
NOT "{"
Seems like the x
got picked up by <A>. I would have liked it to match !‘{’, so that the next char could match in <OPEN>
try changing the OPEN
and CLOSE
rules to
<OPEN> = '{' !'{'
<CLOSE> = '}' !'}'
😄
That seems to work.
The problem in the original grammar was that the negative lookahead was conflicting with the token itself. It was basically saying "If there isn't an open bracket, please parse an open bracket"
Whereas what you really want is "Please parse an open bracket but only if there isn't another open bracket right after"
hmm.. ok, i think that makes sense to me.
Very cool. Thanks for the quick help!
no problem
Here’s an edge case that still fails. But it’s a bit contrived, so if it’s not a trivial fix, I don’t need to worry about it.
(p "{{y}")
do you want that to parse as normal text?
yep
not a block
maybe something like
<S> = TXT*
block = <'{{'> TXT <'}}'>
<TXT> = (block / A)*
<A> = #'[^{}]*' | '{' | '}'
here I'm changing the A
rule to match any text (including brackets and double brackets) but then using the ordered choice (`/`) to prefer parsing complete blocks when possible.
oh.. that’s great. I had tried an approach like that previously, but didn’t know how to prefer one parse over another … that /
operator is new to me.
👍
thanks for your help, again
np