anhldbk
anhldbk

Reputation: 4587

How to make PyParsing recognize \x escapes?

I want to use PyParsing to parse BNF-based rules. A rule may look like:

A -> 'You can use \xABCD to display hexadecimal numbers'

Where A is a nonterminal symbol. The assignment operand is '->'. The last item is a quoted string.

I use PyParsing in the following manner:

Left= Word(alphanums)
Op = oneOf('= := -> ::=')
Right = QuotedString('"') | QuotedString("'")
Rule = Left+ Op+ Right
Rule.parseString("A -> '_\x5555 a'")  # Get an error of ValueError: invalid \x escape

So would you please tell me how to regconize \x escapes with QuotedString? Any help would be appreciated.

Upvotes: 2

Views: 174

Answers (2)

PaulMcG
PaulMcG

Reputation: 63747

If you are going to embed '\'s in your input string, be sure to precede the leading quote with 'r' so that the Python interpreter leaves all the '\'s, instead of interpreting them as escapes.

From the Python console (Python 3.3):

>>> Left= Word(alphanums)
>>> Op = oneOf('= := -> ::=')
>>> Right = QuotedString('"') | QuotedString("'")
>>> Rule = Left+ Op+ Right
>>> Rule.parseString("A -> '_\x5555 a'")
(['A', '->', '_U55 a'], {})
>>> Rule.parseString(r"A -> '_\x5555 a'")  # use a raw string literal, with r""
(['A', '->', '_\\x5555 a'], {})

Upvotes: 3

nneonneo
nneonneo

Reputation: 179592

Just use \\ to escape the \:

"A -> '_\\x5555 a'"

Upvotes: 1

Related Questions