|
Re: [Pyparsing] White space
From: Paul McGuire <ptmcg@au...> - 2011-06-22 00:56
|
Eike -
Good point! It isn't necessary to make '$' the Literal expression, it is
just as good (and if using Keyword, probably more appropriate) to make 'as'
the expression using the Keyword class.
-- Paul
-----Original Message-----
From: Eike Welk [mailto:eike.welk@...]
Sent: Tuesday, June 21, 2011 7:24 PM
To: pyparsing-users@...
Subject: Re: [Pyparsing] White space
Hello Cathal!
I'm trying to answer your question without testing anything. So it might be
completely wrong.
On Wednesday 22.06.2011 00:34:49 cathal coffey wrote:
> Hello,
>
> I have a quick question. Shouldn't the below grammar accept the given
> string?
>
> from pyparsing import Word, alphas
> g = "$" + "as" + Word(alphas)
> g.parseString('$ as abc')
> ParseException: Expected "$as" (at char 0), (line:1, col:1)
It the order with which the ``+`` operators are applied in the first
statement, that fools you.
The left ``+`` operator is applied first so that two strings are added::
"$" + "as"
Therefor your first statement is equivalent to::
g = "$as" + Word(alphas)
You get the desired result with::
g = Literal("$") + "as" + Word(alphas)
Look also at ``Keyword``. You probably want::
from pyparsing import Word, alphas, Keyword
Kw = Keyword
g = "$" + Kw("as") + Word(alphas)
The string ``"$"`` is now implicitly converted to ``Literal("$")`` because
to
apply the left ``+`` operator, Python calls the method ``Keyword.__radd__``.
This method converts strings to literals. For the behavior of Python's
operators look at the official (but somewhat cryptic) explanation:
http://docs.python.org/reference/datamodel.html#emulating-numeric-types
>
> I want the grammar to accept $ followed by: any number of spaces
> followed by: as followed by: any number of spaces followed by: any
> string of characters.
HTH,
Eike.
----------------------------------------------------------------------------
--
EditLive Enterprise is the world's most technically advanced content
authoring tool. Experience the power of Track Changes, Inline Image
Editing and ensure content is compliant with Accessibility Checking.
http://p.sf.net/sfu/ephox-dev2dev
_______________________________________________
Pyparsing-users mailing list
Pyparsing-users@...
https://lists.sourceforge.net/lists/listinfo/pyparsing-users
|
| Thread | Author | Date | |
|---|---|---|---|
| [Pyparsing] White space | cathal coffey <coffey.cathal@gm...> |
|
|
|
|