Closed jenstroeger closed 2 years ago
I'd recommend always using r"""strings"""
to define your grammar. It's also a good idea to use r"strings"
in string literals for regex expressions. Under the hood there are a few levels of \\\\escaping being unpacked, so to include backslash literals, you need to escape them several times. However, with r-strings, both of your grammars compile:
>>> g1 = Grammar(r"""
... cmd = esc ~"[a-zA-Z]"+
... esc = ~r"[\\]"
... """)
>>>
>>> g2 = Grammar(r"""
... cmd = esc ~"[a-zA-Z]"+
... esc = "\\"
... """)
>>> g1.parse('\\abcd')
s = '\\abcd'
Node(<Sequence cmd = esc ~'[a-zA-Z]'u+>, s, 0, 5, children=[RegexNode(<Regex esc = ~'[\\\\]'u>, s, 0, 1), Node(<OneOrMore ~'[a-zA-Z]'u+>, s, 1, 5, children=[RegexNode(<Regex ~'[a-zA-Z]'u>, s, 1, 2), RegexNode(<Regex ~'[a-zA-Z]'u>, s, 2, 3), RegexNode(<Regex ~'[a-zA-Z]'u>, s, 3, 4), RegexNode(<Regex ~'[a-zA-Z]'u>, s, 4, 5)])])
>>> g2.parse('\\abcd')
s = '\\abcd'
Node(<Sequence cmd = esc ~'[a-zA-Z]'u+>, s, 0, 5, children=[Node(<Literal esc = '\\'>, s, 0, 1), Node(<OneOrMore ~'[a-zA-Z]'u+>, s, 1, 5, children=[RegexNode(<Regex ~'[a-zA-Z]'u>, s, 1, 2), RegexNode(<Regex ~'[a-zA-Z]'u>, s, 2, 3), RegexNode(<Regex ~'[a-zA-Z]'u>, s, 3, 4), RegexNode(<Regex ~'[a-zA-Z]'u>, s, 4, 5)])])
The docs should maybe be updated to reflect this advice.
It looks like declaring a
\
backslash character as a literal yields problems? For example, using a simple grammar:works when I want to use
!
as a “command escape” character. However…If I try to use a regex:
Related to issue https://github.com/erikrose/parsimonious/pull/135?