U ë˜RexŠãi@sÖ dZdZdZdZddlZddlmZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZzddlmZWn ek r¨ddlmZYnXzdd lmZdd lmZWn,ek ròdd l mZdd l mZYnXzdd l mZWnBek �rFzdd lmZWnek �r@dZYnXYnXd d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtgiZee jƒddu…ZeddukZ e �rpe j!Z"e#Z$e%Z&e#Z'e(e)e*e+e,ee-e.e/e0e1g Z2n`e j3Z"e4Z5dvdw„Z'gZ2ddl6Z6dx 7¡D]8Z8ze2 9e:e6e8ƒ¡Wne;k �rÊY�q–YnX�q–eGd~d„de?ƒZ@ejAejBZCd€ZDeDd�ZEeCeDZFe%d‚ƒZGdƒ Hd„dz„ejIDƒ¡ZJGd…d#„d#eKƒZLGd†d%„d%eLƒZMGd‡d'„d'eLƒZNGdˆd)„d)eNƒZOGd‰d,„d,eKƒZPGdŠd‹„d‹e?ƒZQGdŒd(„d(e?ƒZRe SeR¡d�d?„ZTdŽdP„ZUd�dM„ZVd�d‘„ZWd’d“„ZXd”d•„ZYd–dW„ZZ�d/d˜d™„Z[Gdšd*„d*e?ƒZ\Gd›d2„d2e\ƒZ]Gdœd„de]ƒZ^Gd�d„de]ƒZ_Gdžd„de]ƒZ`e`Zae`e\_bGdŸd„de]ƒZcGd d„de`ƒZdGd¡d „d ecƒZeGd¢dr„dre]ƒZfGd£d5„d5e]ƒZgGd¤d-„d-e]ƒZhGd¥d+„d+e]ƒZiGd¦d„de]ƒZjGd§d4„d4e]ƒZkGd¨d©„d©e]ƒZlGdªd„delƒZmGd«d„delƒZnGd¬d„delƒZoGd­d0„d0elƒZpGd®d/„d/elƒZqGd¯d7„d7elƒZrGd°d6„d6elƒZsGd±d&„d&e\ƒZtGd²d „d etƒZuGd³d"„d"etƒZvGd´d„detƒZwGdµd„detƒZxGd¶d$„d$e\ƒZyGd·d„deyƒZzGd¸d„deyƒZ{Gd¹dº„dºeyƒZ|Gd»d„de|ƒZ}Gd¼d8„d8e|ƒZ~Gd½d¾„d¾e?ƒZeƒZ€Gd¿d!„d!eyƒZ�GdÀd.„d.eyƒZ‚GdÁd„deyƒZƒGdÂdÄdÃeƒƒZ„GdÄd3„d3eyƒZ…GdÅd„de…ƒZ†GdÆd„de…ƒZ‡GdÇd„de…ƒZˆGdÈd1„d1e…ƒZ‰GdÉd „d e?ƒZŠdÊdh„Z‹�d0dÍdF„ZŒ�d1dÎdB„Z�dÏdЄZŽdÑdU„Z�dÒdT„Z�dÓdÔ„Z‘�d2dÖdY„Z’d×dG„Z“�d3dØdm„Z”dÙdn„Z•dÚdp„Z–e^ƒ —dI¡Z˜enƒ —dO¡Z™eoƒ —dN¡Zšepƒ —dg¡Z›eqƒ —df¡ZœegeGdÛd—dÜ� �dÝdÞ„¡Zžehd߃ �dàdÞ„¡ZŸehdრ�dâdÞ„¡Z ežeŸBe Bejdãd{dÜ�BZ¡e‡e¡e‰däƒe¡ƒZ¢e`dåƒe�d惠£dç¡e‡e}e¢e¡Bƒƒ £dè¡déZ¤dêde„Z¥dëdS„Z¦dìdb„Z§díd`„Z¨dîds„Z©e©dïdÞ„ƒZªe©dðdÞ„ƒZ«dñdò„Z¬dódQ„Z­dôdR„Z®dõdk„Z¯e?ƒe¯_°�d4dödq„Z±e@ƒZ²e?ƒe²_³e?ƒe²_´e‰d÷ƒe‰døƒfdùdo„ZµeµZ¶e†ehdúƒdûƒ —dü¡Z·e†ehdýƒdþƒ —dÿ¡Z¸e†ehdúƒdûehdýƒdþBƒ —�d¡Z¹e†ea�dƒe¹ ¡ƒ —�d¡Zºd÷døde¹ ¡f�ddV„Z»�d5�ddl„Z¼e¥�dƒZ½e¥�dƒZ¾e­egeCeF�dƒ —�d¡ƒ\Z¿ZÀeÁeÂ�d  7¡�d ƒƒZÃeh�d �d  Heàġ¡�d ƒ —�d¡ZÅ�dda„ZÆe†eh�dƒ�dƒ —�d¡ZÇeh�dƒ —�d¡ZÈeh�dƒ É¡ —�d¡ZÊeh�dƒ —�d¡ZËe†eh�dƒ�deËBƒ —�d¡ZÌeÌZÍeh�dƒ —�d¡ZÎe†e}egeJdË�d�e�eg�dƒe`d˃eoƒƒƒƒ Ï¡ —�d¡ZÐeŒe�e¹ ¡eÐBdƒ�d�ƒ —d@¡ZÑG�d dt„dtƒZÒeÓ�d!k� rÒed�d"ƒZÔed�d#ƒZÕegeCeF�d$ƒZÖeŒeÖ�d%dÕ�d&� �eª¡Z×e‡eŒe׃ƒ —�d'¡ZØ�d(eØBZÙeŒeÖ�d%dÕ�d&� �eª¡ZÚe‡eŒeÚƒƒ —�d)¡ZÛeÔ�d*ƒeÙ�d'ƒeÕeÛ�d)ƒZÜeÜ Ý�d+¡eÒjÞ Ý�d,¡eÒjß Ý�d,¡eÒjà Ý�d-¡ddláZáeÒjá �e©eáj⃡eÒjá Ý�d.¡dS(6aÜ pyparsing module - Classes and methods to define and execute parsing grammars ============================================================================= The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python. Here is a program to parse "Hello, World!" (or any greeting of the form C{", !"}), built up using L{Word}, L{Literal}, and L{And} elements (L{'+'} operator gives L{And} expressions, strings are auto-converted to L{Literal} expressions):: from pyparsing import Word, alphas # define grammar of a greeting greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) The program outputs the following:: Hello, World! -> ['Hello', ',', 'World', '!'] The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of '+', '|' and '^' operators. The L{ParseResults} object returned from L{ParserElement.parseString} can be accessed as a nested list, a dictionary, or an object with named attributes. The pyparsing module handles some of the problems that are typically vexing when writing text parsers: - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.) - quoted strings - embedded comments Getting Started - ----------------- Visit the classes L{ParserElement} and L{ParseResults} to see the base classes that most other pyparsing classes inherit from. Use the docstrings for examples of how to: - construct literal match expressions from L{Literal} and L{CaselessLiteral} classes - construct character word-group expressions using the L{Word} class - see how to create repetitive expressions using L{ZeroOrMore} and L{OneOrMore} classes - use L{'+'}, L{'|'}, L{'^'}, and L{'&'} operators to combine simple expressions into more complex ones - associate names with your parsed results using L{ParserElement.setResultsName} - find some helpful expression short-cuts like L{delimitedList} and L{oneOf} - find more useful common expressions in the L{pyparsing_common} namespace class z2.2.1z18 Sep 2018 00:49 UTCz*Paul McGuire éN)Úref)Údatetime)ÚRLock)ÚIterable)ÚMutableMapping)Ú OrderedDictÚAndÚCaselessKeywordÚCaselessLiteralÚ CharsNotInÚCombineÚDictÚEachÚEmptyÚ FollowedByÚForwardÚ GoToColumnÚGroupÚKeywordÚLineEndÚ LineStartÚLiteralÚ MatchFirstÚNoMatchÚNotAnyÚ OneOrMoreÚOnlyOnceÚOptionalÚOrÚParseBaseExceptionÚParseElementEnhanceÚParseExceptionÚParseExpressionÚParseFatalExceptionÚ ParseResultsÚParseSyntaxExceptionÚ ParserElementÚ QuotedStringÚRecursiveGrammarExceptionÚRegexÚSkipToÚ StringEndÚ StringStartÚSuppressÚTokenÚTokenConverterÚWhiteÚWordÚWordEndÚ WordStartÚ ZeroOrMoreÚ alphanumsÚalphasÚ alphas8bitÚ anyCloseTagÚ anyOpenTagÚ cStyleCommentÚcolÚcommaSeparatedListÚcommonHTMLEntityÚ countedArrayÚcppStyleCommentÚdblQuotedStringÚdblSlashCommentÚ delimitedListÚdictOfÚdowncaseTokensÚemptyÚhexnumsÚ htmlCommentÚjavaStyleCommentÚlineÚlineEndÚ lineStartÚlinenoÚ makeHTMLTagsÚ makeXMLTagsÚmatchOnlyAtColÚmatchPreviousExprÚmatchPreviousLiteralÚ nestedExprÚnullDebugActionÚnumsÚoneOfÚopAssocÚoperatorPrecedenceÚ printablesÚpunc8bitÚpythonStyleCommentÚ quotedStringÚ removeQuotesÚreplaceHTMLEntityÚ replaceWithÚ restOfLineÚsglQuotedStringÚsrangeÚ stringEndÚ stringStartÚtraceParseActionÚ unicodeStringÚ upcaseTokensÚ withAttributeÚ indentedBlockÚoriginalTextForÚungroupÚ infixNotationÚ locatedExprÚ withClassÚ CloseMatchÚtokenMapÚpyparsing_commonécCsft|tƒr|Sz t|ƒWStk r`t|ƒ t ¡d¡}tdƒ}| dd„¡|  |¡YSXdS)aDrop-in replacement for str(obj) that tries to be Unicode friendly. It first tries str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It then < returns the unicode object | encodes it with the default encoding | ... >. Úxmlcharrefreplacez&#\d+;cSs$dtt|ddd…ƒƒdd…S)Nz\urééÿÿÿÿ)ÚhexÚint©Út©ryú’/builddir/build/BUILDROOT/alt-python38-setuptools-58.3.0-2.el8.x86_64/opt/alt/python38/lib/python3.8/site-packages/setuptools/_vendor/pyparsing.pyÚ«óz_ustr..N) Ú isinstanceÚunicodeÚstrÚUnicodeEncodeErrorÚencodeÚsysÚgetdefaultencodingr)ÚsetParseActionÚtransformString)ÚobjÚretZ xmlcharrefryryrzÚ_ustršs  rˆz6sum len sorted reversed list tuple set any all min maxccs|] }|VqdS©Nry)Ú.0ÚyryryrzÚ ·srŒécCs:d}dd„d ¡Dƒ}t||ƒD]\}}| ||¡}q |S)z/Escape &, <, >, ", ', etc. in a string of data.z&><"'css|]}d|dVqdS)ú&ú;Nry)rŠÚsryryrzrŒ¾sz_xml_escape..zamp gt lt quot apos)ÚsplitÚzipÚreplace)ÚdataZ from_symbolsZ to_symbolsZfrom_Zto_ryryrzÚ _xml_escape¹s r•c@s eZdZdS)Ú _ConstantsN)Ú__name__Ú __module__Ú __qualname__ryryryrzr–Ãsr–Ú 0123456789Z ABCDEFabcdefé\Úccs|]}|tjkr|VqdSr‰)ÚstringÚ whitespace©rŠÚcryryrzrŒËs c@sPeZdZdZddd„Zedd„ƒZdd „Zd d „Zd d „Z ddd„Z dd„Z dS)rz7base exception class for all parsing runtime exceptionsrNcCs>||_|dkr||_d|_n ||_||_||_|||f|_dS©Nrœ)ÚlocÚmsgÚpstrÚ parserElementÚargs)Úselfr¤r¢r£ÚelemryryrzÚ__init__ÑszParseBaseException.__init__cCs||j|j|j|jƒS)z­ internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses )r¤r¢r£r¥)ÚclsÚperyryrzÚ_from_exceptionÜsz"ParseBaseException._from_exceptioncCsN|dkrt|j|jƒS|dkr,t|j|jƒS|dkrBt|j|jƒSt|ƒ‚dS)z÷supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text rL)r;ÚcolumnrIN)rLr¢r¤r;rIÚAttributeError)r§ZanameryryrzÚ __getattr__äszParseBaseException.__getattr__cCsd|j|j|j|jfS)Nz"%s (at char %d), (line:%d, col:%d))r£r¢rLr­©r§ryryrzÚ__str__ósÿzParseBaseException.__str__cCst|ƒSr‰©rˆr°ryryrzÚ__repr__öszParseBaseException.__repr__ú>!} ('-' operator) indicates that parsing is to stop immediately because an unbacktrackable syntax error has been foundNrÀryryryrzr%sc@s eZdZdZdd„Zdd„ZdS)r(zZexception thrown by L{ParserElement.validate} if the grammar could be improperly recursivecCs ||_dSr‰©ÚparseElementTrace©r§ÚparseElementListryryrzr©4sz"RecursiveGrammarException.__init__cCs d|jS)NzRecursiveGrammarException: %srÁr°ryryrzr±7sz!RecursiveGrammarException.__str__N)r—r˜r™r¾r©r±ryryryrzr(2sc@s,eZdZdd„Zdd„Zdd„Zdd„Zd S) Ú_ParseResultsWithOffsetcCs||f|_dSr‰©Útup)r§Úp1Úp2ryryrzr©;sz _ParseResultsWithOffset.__init__cCs |j|Sr‰rÆ©r§ÚiryryrzÚ __getitem__=sz#_ParseResultsWithOffset.__getitem__cCst|jdƒS©Nr)ÚreprrÇr°ryryrzr³?sz _ParseResultsWithOffset.__repr__cCs|jd|f|_dSrÍrÆrÊryryrzÚ setOffsetAsz!_ParseResultsWithOffset.setOffsetN)r—r˜r™r©rÌr³rÏryryryrzrÅ:srÅc@sœeZdZdZd[dd„Zddddefdd„Zdd „Zefd d „Zd d „Z dd„Z dd„Z dd„Z e Z dd„Zdd„Zdd„Zdd„Zdd„ZerœeZeZeZn$eZeZeZdd„Zd d!„Zd"d#„Zd$d%„Zd&d'„Zd\d(d)„Zd*d+„Zd,d-„Zd.d/„Zd0d1„Z d2d3„Z!d4d5„Z"d6d7„Z#d8d9„Z$d:d;„Z%d} - see L{ParserElement.setResultsName}) Example:: integer = Word(nums) date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: # date_str = integer("year") + '/' + integer("month") + '/' + integer("day") # parseString returns a ParseResults object result = date_str.parseString("1999/12/31") def test(s, fn=repr): print("%s -> %s" % (s, fn(eval(s)))) test("list(result)") test("result[0]") test("result['month']") test("result.day") test("'month' in result") test("'minutes' in result") test("result.dump()", str) prints:: list(result) -> ['1999', '/', '12', '/', '31'] result[0] -> '1999' result['month'] -> '12' result.day -> '31' 'month' in result -> True 'minutes' in result -> False result.dump() -> ['1999', '/', '12', '/', '31'] - day: 31 - month: 12 - year: 1999 NTcCs"t||ƒr|St |¡}d|_|S©NT)r}ÚobjectÚ__new__Ú_ParseResults__doinit)rªÚtoklistÚnameÚasListÚmodalZretobjryryrzrÒks   zParseResults.__new__c Csb|jrvd|_d|_d|_i|_||_||_|dkr6g}||tƒrP|dd…|_n||tƒrft|ƒ|_n|g|_t ƒ|_ |dk �r^|�r^|s”d|j|<||t ƒr¦t |ƒ}||_||t dƒttfƒrÐ|ddgfk�s^||tƒrà|g}|�r(||tƒ�rt| ¡dƒ||<ntt|dƒdƒ||<|||_n6z|d||<Wn$tttfk �r\|||<YnXdS)NFrrœ)rÓÚ_ParseResults__nameÚ_ParseResults__parentÚ_ParseResults__accumNamesÚ_ParseResults__asListÚ_ParseResults__modalÚlistÚ_ParseResults__toklistÚ_generatorTypeÚdictÚ_ParseResults__tokdictrvrˆr¼Ú basestringr$rÅÚcopyÚKeyErrorÚ TypeErrorÚ IndexError)r§rÔrÕrÖr×r}ryryrzr©tsB     $   zParseResults.__init__cCsPt|ttfƒr|j|S||jkr4|j|ddStdd„|j|DƒƒSdS)NrtrcSsg|] }|d‘qS©rry©rŠÚvryryrzÚ ¢sz,ParseResults.__getitem__..)r}rvÚslicerÞrÚrár$rÊryryrzrÌ›s   zParseResults.__getitem__cCsŒ||tƒr0|j |tƒ¡|g|j|<|d}nD||ttfƒrN||j|<|}n&|j |tƒ¡t|dƒg|j|<|}||tƒrˆt|ƒ|_ dSrÍ) rÅráÚgetrÝrvrërÞr$ÚwkrefrÙ)r§Úkrér}ÚsubryryrzÚ __setitem__¤s   " zParseResults.__setitem__c Csºt|ttfƒr®t|jƒ}|j|=t|tƒrH|dkr:||7}t||dƒ}tt| |¡Žƒ}| ¡|j   ¡D]>\}}|D]0}t |ƒD]"\}\}} t || | |kƒ||<q„qxqln|j |=dS©Nrr�) r}rvrëÚlenrÞrÝÚrangeÚindicesÚreverseráÚitemsÚ enumeraterÅ) r§rËÚmylenÚremovedrÕÚ occurrencesÚjrîÚvalueÚpositionryryrzÚ __delitem__±s  zParseResults.__delitem__cCs ||jkSr‰)rá)r§rîryryrzÚ __contains__ÆszParseResults.__contains__cCs t|jƒSr‰)ròrÞr°ryryrzÚ__len__Ér|zParseResults.__len__cCs |j Sr‰©rÞr°ryryrzÚ__bool__Êr|zParseResults.__bool__cCs t|jƒSr‰©ÚiterrÞr°ryryrzÚ__iter__Ìr|zParseResults.__iter__cCst|jddd…ƒS©Nrtrr°ryryrzÚ __reversed__Ír|zParseResults.__reversed__cCs$t|jdƒr|j ¡St|jƒSdS)NÚiterkeys)Úhasattrrárrr°ryryrzÚ _iterkeysÎs  zParseResults._iterkeyscs‡fdd„ˆ ¡DƒS)Nc3s|]}ˆ|VqdSr‰ry©rŠrîr°ryrzrŒÕsz+ParseResults._itervalues..©r r°ryr°rzÚ _itervaluesÔszParseResults._itervaluescs‡fdd„ˆ ¡DƒS)Nc3s|]}|ˆ|fVqdSr‰ryr r°ryrzrŒØsz*ParseResults._iteritems..r r°ryr°rzÚ _iteritems×szParseResults._iteritemscCs t| ¡ƒS)zVReturns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).)rÝrr°ryryrzÚkeysîszParseResults.keyscCs t| ¡ƒS)zXReturns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).)rÝÚ itervaluesr°ryryrzÚvaluesòszParseResults.valuescCs t| ¡ƒS)zfReturns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).)rÝÚ iteritemsr°ryryrzrööszParseResults.itemscCs t|jƒS)z�Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.)Úboolrár°ryryrzÚhaskeysúszParseResults.haskeyscOsŽ|s dg}| ¡D]*\}}|dkr0|d|f}qtd|ƒ‚qt|dtƒsdt|ƒdksd|d|kr~|d}||}||=|S|d}|SdS)a¹ Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321'] rtÚdefaultrz-pop() got an unexpected keyword argument '%s'r�N)rörår}rvrò)r§r¦ÚkwargsrîréÚindexr‡Ú defaultvalueryryrzÚpopÿs"" ÿ þzParseResults.popcCs||kr||S|SdS)ai Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None Nry)r§ÚkeyÚ defaultValueryryrzrì3szParseResults.getcCsR|j ||¡|j ¡D]4\}}t|ƒD]"\}\}}t||||kƒ||<q(qdS)a Inserts new element at location index in the list of parsed tokens. Similar to C{list.insert()}. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed results def insert_locn(locn, tokens): tokens.insert(0, locn) print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321'] N)rÞÚinsertrárör÷rÅ)r§rZinsStrrÕrúrîrürýryryrzrIszParseResults.insertcCs|j |¡dS)aþ Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] N)rÞÚappend)r§Úitemryryrzr]s zParseResults.appendcCs$t|tƒr||7}n |j |¡dS)a Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' N)r}r$rÞÚextend)r§Úitemseqryryrzrks  zParseResults.extendcCs|jdd…=|j ¡dS)z7 Clear all elements and results names. N)rÞráÚclearr°ryryrzr!}s zParseResults.clearcCsjz ||WStk r YdSX||jkrb||jkrH|j|ddStdd„|j|DƒƒSndSdS)NrœrtrcSsg|] }|d‘qSrçryrèryryrzrêŽsz,ParseResults.__getattr__..)rärárÚr$©r§rÕryryrzr¯„s   zParseResults.__getattr__cCs| ¡}||7}|Sr‰©rã)r§Úotherr‡ryryrzÚ__add__’szParseResults.__add__csŒ|jrjt|jƒ‰‡fdd„‰|j ¡}‡fdd„|Dƒ}|D],\}}|||<t|dtƒr.c s4g|],\}}|D]}|t|dˆ|dƒƒf‘qqS©rr�)rÅ©rŠrîÚvlistré)Ú addoffsetryrzrêœsÿz)ParseResults.__iadd__..r) ráròrÞrör}r$rírÙrÚÚupdate)r§r$Ú otheritemsÚotherdictitemsrîréry)r+r'rzÚ__iadd__—s    ÿ zParseResults.__iadd__cCs&t|tƒr|dkr| ¡S||SdSrÍ)r}rvrã©r§r$ryryrzÚ__radd__§szParseResults.__radd__cCsdt|jƒt|jƒfS)Nz(%s, %s))rÎrÞrár°ryryrzr³¯szParseResults.__repr__cCsdd dd„|jDƒ¡dS)Nú[ú, css(|] }t|tƒrt|ƒnt|ƒVqdSr‰)r}r$rˆrΩrŠrËryryrzrŒ³sz'ParseResults.__str__..ú])rµrÞr°ryryrzr±²szParseResults.__str__rœcCsLg}|jD]<}|r |r | |¡t|tƒr8|| ¡7}q | t|ƒ¡q |Sr‰)rÞrr}r$Ú _asStringListrˆ)r§ÚsepÚoutrryryrzr6µs   zParseResults._asStringListcCsdd„|jDƒS)aƒ Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> ['sldkj', 'lsdkj', 'sldkj'] cSs"g|]}t|tƒr| ¡n|‘qSry)r}r$rÖ)rŠÚresryryrzrêÎsz'ParseResults.asList..rr°ryryrzrÖÀszParseResults.asListcs6tr |j}n|j}‡fdd„‰t‡fdd„|ƒDƒƒS)aà Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} cs6t|tƒr.| ¡r| ¡S‡fdd„|DƒSn|SdS)Ncsg|] }ˆ|ƒ‘qSryryrè©ÚtoItemryrzrêísz7ParseResults.asDict..toItem..)r}r$rÚasDict)r†r:ryrzr;ès  z#ParseResults.asDict..toItemc3s|]\}}|ˆ|ƒfVqdSr‰ry©rŠrîrér:ryrzrŒñsz&ParseResults.asDict..)ÚPY_3rörrà)r§Zitem_fnryr:rzr<Ðs  zParseResults.asDictcCs8t|jƒ}|j ¡|_|j|_|j |j¡|j|_|S)zA Returns a new copy of a C{ParseResults} object. )r$rÞrárãrÙrÚr,rØ©r§r‡ryryrzrãós   zParseResults.copyFc CsLd}g}tdd„|j ¡Dƒƒ}|d}|s8d}d}d}d} |dk rJ|} n |jrV|j} | sf|rbdSd} |||d| d g7}t|jƒD]¬\} } t| tƒrà| |krÀ||  || |o²|dk||¡g7}n||  d|oÒ|dk||¡g7}q‚d} | |krô|| } | �s|�rq‚nd} t t | ƒƒ} |||d| d | d | d g 7}q‚|||d | d g7}d  |¡S) z‡ (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. Ú css(|] \}}|D]}|d|fVqqdS©r�Nryr)ryryrzrŒsÿz%ParseResults.asXML..ú rœNZITEMú<ú>ú.z %s%s- %s: rBr�css|]}t|tƒVqdSr‰)r}r$)rŠÚvvryryrzrŒŠsz %s%s[%d]: %s%s%srœ) rrˆrÖrÚsortedrör}r$ÚdumprÎÚanyr÷rµ) r§rGÚdepthÚfullr8ÚNLrörîrérËrNryryrzrPgs,    4,zParseResults.dumpcOstj| ¡f|ž|ŽdS)aõ Pretty-printer for parsed results as a list, using the C{pprint} module. Accepts additional positional or keyword args as defined for the C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint}) Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(delimitedList(term))) result = func.parseString("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] N)ÚpprintrÖ©r§r¦rryryrzrU”szParseResults.pprintcCs.|j|j ¡|jdk r| ¡p d|j|jffSr‰)rÞrárãrÙrÚrØr°ryryrzÚ __getstate__¬sýÿzParseResults.__getstate__cCsN|d|_|d\|_}}|_i|_|j |¡|dk rDt|ƒ|_nd|_dSrñ)rÞrárØrÚr,rírÙ)r§ÚstaterLÚ inAccumNamesryryrzÚ __setstate__³s ý  zParseResults.__setstate__cCs|j|j|j|jfSr‰)rÞrØrÛrÜr°ryryrzÚ__getnewargs__ÀszParseResults.__getnewargs__cCstt|ƒƒt| ¡ƒSr‰)r»r¼rÝrr°ryryrzr½ÃszParseResults.__dir__)NNTT)N)rœ)NFrœT)rœrT)4r—r˜r™r¾rÒr}r©rÌrðrþrÿrrÚ __nonzero__rrr r rr>rrrörrrrrrìrrrr!r¯r%r/r1r³r±r6rÖr<rãrFrJrMrPrUrWrZr[r½ryryryrzr$Dsh& ' 4  # =% - cCsF|}d|krt|ƒkr4nn||ddkr4dS|| dd|¡S)aReturns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}} for more information on parsing strings containing C{}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. rr�r@)ròÚrfind)r¢Ústrgr�ryryrzr;Ès cCs| dd|¡dS)aReturns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}} for more information on parsing strings containing C{}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. r@rr�)Úcount)r¢r^ryryrzrLÕs cCsF| dd|¡}| d|¡}|dkr2||d|…S||dd…SdS)zfReturns the line of text containing loc within a string, counting newlines as line separators. r@rr�N)r]Úfind)r¢r^ZlastCRZnextCRryryrzrIás  cCs8tdt|ƒdt|ƒdt||ƒt||ƒfƒdS)NzMatch z at loc z(%d,%d))ÚprintrˆrLr;)Úinstringr¢ÚexprryryrzÚ_defaultStartDebugActionësrdcCs$tdt|ƒdt| ¡ƒƒdS)NzMatched z -> )rarˆrrÖ)rbÚstartlocÚendlocrcÚtoksryryrzÚ_defaultSuccessDebugActionîsrhcCstdt|ƒƒdS)NzException raised:)rarˆ)rbr¢rcÚexcryryrzÚ_defaultExceptionDebugActionñsrjcGsdS)zG'Do-nothing' debug action, to suppress debugging output during parsing.Nry)r¦ryryrzrSôsrscsÒˆtkr‡fdd„Sdg‰dg‰tdd…dkrFddd„}dd d „‰n tj}tj‰d }|dd �d }|d|d|f‰‡‡‡‡‡‡fdd„}d}ztˆdtˆdƒjƒ}Wntk rÆtˆƒ}YnX||_|S)Ncsˆ|ƒSr‰ry©r�Úlrx)Úfuncryrzr{r|z_trim_arity..rFrs)rqécSs8tdkr dnd}tj| |dd�|}|dd…gS)N)rqrnréýÿÿÿéþÿÿÿr�©Úlimitrs)Úsystem_versionÚ tracebackÚ extract_stack)rrr'Ú frame_summaryryryrzrusz"_trim_arity..extract_stackcSs$tj||d�}|d}|dd…gS)Nrqrtrs)rtÚ extract_tb)ÚtbrrÚframesrvryryrzrwsz_trim_arity..extract_tbérqrtr�c s z"ˆ|ˆdd…Ž}dˆd<|WStk r˜ˆdr>‚n4z.t ¡d}ˆ|dd�ddd…ˆksj‚W5~Xˆdˆkr’ˆdd7<Yq‚YqXqdS)NrTrtrsrqr�)rår‚Úexc_info)r¦r‡rx©rwZ foundArityrmrrÚmaxargsÚpa_call_line_synthryrzÚwrapper-s   z_trim_arity..wrapperzr—Ú __class__)r)r) ÚsingleArgBuiltinsrsrtrurwÚgetattrr—Ú Exceptionr)rmr}ruÚ LINE_DIFFÚ this_linerÚ func_nameryr|rzÚ _trim_aritys,    ÿr‡cs’eZdZdZdZdZedd„ƒZedd„ƒZd†dd „Z d d „Z d d „Z d‡dd„Z dˆdd„Z dd„Zdd„Zdd„Zdd„Zdd„Zdd„Zd‰dd „Zd!d"„ZdŠd#d$„Zd%d&„Zd'd(„ZGd)d*„d*eƒZed+k ràGd,d-„d-eƒZnGd.d-„d-eƒZiZeƒZd/d/gZ d‹d0d1„Z!eZ"ed2d3„ƒZ#dZ$edŒd5d6„ƒZ%d�d7d8„Z&e'dfd9d:„Z(d;d<„Z)e'fd=d>„Z*e'dfd?d@„Z+dAdB„Z,dCdD„Z-dEdF„Z.dGdH„Z/dIdJ„Z0dKdL„Z1dMdN„Z2dOdP„Z3dQdR„Z4dSdT„Z5dUdV„Z6dWdX„Z7dYdZ„Z8dŽd[d\„Z9d]d^„Z:d_d`„Z;dadb„Zdgdh„Z?d�didj„Z@dkdl„ZAdmdn„ZBdodp„ZCdqdr„ZDgfdsdt„ZEd�dudv„ZF‡fdwdx„ZGdydz„ZHd{d|„ZId}d~„ZJdd€„ZKd‘d�d‚„ZLd’d„d…„ZM‡ZNS)“r&z)Abstract base level parser element class.z FcCs |t_dS)aÑ Overrides the default whitespace chars Example:: # default whitespace chars are space, and newline OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.setDefaultWhitespaceChars(" \t") OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] N)r&ÚDEFAULT_WHITE_CHARS©ÚcharsryryrzÚsetDefaultWhitespaceCharsTs z'ParserElement.setDefaultWhitespaceCharscCs |t_dS)a… Set class to be used for inclusion of string literals into a parser. Example:: # default literal class used is Literal integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inlineLiteralsUsing(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '12', '31'] N)r&Ú_literalStringClass)rªryryrzÚinlineLiteralsUsingcsz!ParserElement.inlineLiteralsUsingcCs‚tƒ|_d|_d|_d|_||_d|_tj|_ d|_ d|_ d|_ tƒ|_ d|_d|_d|_d|_d|_d|_d|_d|_d|_dS)NTFrœ)NNN)rÝÚ parseActionÚ failActionÚstrReprÚ resultsNameÚ saveAsListÚskipWhitespacer&rˆÚ whiteCharsÚcopyDefaultWhiteCharsÚmayReturnEmptyÚkeepTabsÚ ignoreExprsÚdebugÚ streamlinedÚ mayIndexErrorÚerrmsgÚ modalResultsÚ debugActionsÚreÚ callPreparseÚ callDuringTry)r§Úsavelistryryrzr©xs(zParserElement.__init__cCs<t |¡}|jdd…|_|jdd…|_|jr8tj|_|S)a$ Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K") integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) prints:: [5120, 100, 655360, 268435456] Equivalent form of C{expr.copy()} is just C{expr()}:: integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") N)rãrŽr˜r•r&rˆr”)r§Úcpyryryrzrã�s  zParserElement.copycCs*||_d|j|_t|dƒr&|j|j_|S)af Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) ú Expected Ú exception)rÕrœr r¥r£r"ryryrzÚsetName¦s    zParserElement.setNamecCs4| ¡}| d¡r"|dd…}d}||_| |_|S)aP Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") Ú*NrtT)rãÚendswithr‘r�)r§rÕÚlistAllMatchesÚnewselfryryrzÚsetResultsName´s  zParserElement.setResultsNameTcs@|r&|j‰d‡fdd„ }ˆ|_||_nt|jdƒr<|jj|_|S)z¦Method to invoke the Python pdb debugger when this element is about to be parsed. Set C{breakFlag} to True to enable, False to disable. Tcsddl}| ¡ˆ||||ƒSrÍ)ÚpdbÚ set_trace)rbr¢Ú doActionsÚ callPreParser¬©Ú _parseMethodryrzÚbreaker×sz'ParserElement.setBreak..breakerÚ_originalParseMethod)TT)Ú_parser³r )r§Z breakFlagr²ryr°rzÚsetBreakÐs  zParserElement.setBreakcOs&tttt|ƒƒƒ|_| dd¡|_|S)a Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}} for more information on parsing strings containing C{}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] r¡F)rÝÚmapr‡rŽrìr¡©r§Úfnsrryryrzr„âs"zParserElement.setParseActioncOs4|jtttt|ƒƒƒ7_|jp,| dd¡|_|S)z³ Add one or more parse actions to expression's list of parse actions. See L{I{setParseAction}}. See examples in L{I{copy}}. r¡F)rŽrÝr¶r‡r¡rìr·ryryrzÚaddParseActionszParserElement.addParseActioncs^| dd¡‰| dd¡rtnt‰|D] ‰‡‡‡fdd„}|j |¡q$|jpV| dd¡|_|S)aÓAdd a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) Úmessagezfailed user-defined conditionÚfatalFcs$ttˆƒ|||ƒƒs ˆ||ˆƒ‚dSr‰)rr‡rk©Úexc_typeÚfnr£ryrzÚpa&sz&ParserElement.addCondition..par¡)rìr#r!rŽrr¡)r§r¸rr¿ryr¼rzÚ addConditions zParserElement.addConditioncCs ||_|S)a Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments C{fn(s,loc,expr,err)} where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw C{L{ParseFatalException}} if it is desired to stop parsing immediately.)r�)r§r¾ryryrzÚ setFailAction-s zParserElement.setFailActionc CsNd}|rJd}|jD]4}z| ||¡\}}d}qWqtk rDYqXqq|S©NTF)r˜r´r!)r§rbr¢Ú exprsFoundÚeÚdummyryryrzÚ_skipIgnorables:s   zParserElement._skipIgnorablescCsH|jr| ||¡}|jrD|j}t|ƒ}||krD|||krD|d7}q&|S©Nr�)r˜rÆr“r”rò)r§rbr¢ÚwtÚinstrlenryryrzÚpreParseGs  zParserElement.preParsecCs|gfSr‰ry©r§rbr¢r®ryryrzÚ parseImplSszParserElement.parseImplcCs|Sr‰ry©r§rbr¢Ú tokenlistryryrzÚ postParseVszParserElement.postParsec CsÎ|j}|s|jrì|jdr,|jd|||ƒ|rD|jrD| ||¡}n|}|}zDz| |||¡\}}Wn(tk rŒt|t|ƒ|j |ƒ‚YnXWnXt k rè} z:|jdrÀ|jd|||| ƒ|jrÖ| |||| ¡‚W5d} ~ XYnXn�|�r|j�r| ||¡}n|}|}|j �s&|t|ƒk�rjz| |||¡\}}Wn*tk �rft|t|ƒ|j |ƒ‚YnXn| |||¡\}}|  |||¡}t ||j|j|jd�} |j�rž|�s¶|j�rž|�rTzN|jD]B} | ||| ƒ}|dk �rÄt ||j|j�oút|t tfƒ|jd�} �qÄWnFt k �rP} z&|jd�r>|jd|||| ƒ‚W5d} ~ XYnXnJ|jD]B} | ||| ƒ}|dk �rZt ||j|j�o�t|t tfƒ|jd�} �qZ|�rÆ|jd�rÆ|jd||||| ƒ|| fS)Nrrs)rÖr×r�)r™r�ržr rÊrÌrær!ròrœrr›rÏr$r‘r’r�rŽr¡r}rÝ) r§rbr¢r®r¯Ú debuggingÚprelocZ tokensStartÚtokensÚerrZ retTokensr¾ryryrzÚ _parseNoCacheZst       ý    ý  zParserElement._parseNoCachecCs@z|j||dd�dWStk r:t|||j|ƒ‚YnXdS)NF)r®r)r´r#r!rœ©r§rbr¢ryryrzÚtryParse¡szParserElement.tryParsec Cs4z| ||¡Wnttfk r*YdSXdSdS)NFT)rÖr!rærÕryryrzÚ canParseNext§s zParserElement.canParseNextc@seZdZdd„ZdS)zParserElement._UnboundedCachecs~i‰tƒ|_‰‡‡fdd„}‡fdd„}‡fdd„}‡fdd„}t ||¡|_t ||¡|_t ||¡|_t ||¡|_dS) Ncs ˆ |ˆ¡Sr‰©rì©r§r©ÚcacheÚ not_in_cacheryrzrì´sz3ParserElement._UnboundedCache.__init__..getcs |ˆ|<dSr‰ry©r§rrü©rÛryrzÚset·sz3ParserElement._UnboundedCache.__init__..setcs ˆ ¡dSr‰©r!r°rÞryrzr!ºsz5ParserElement._UnboundedCache.__init__..clearcstˆƒSr‰©ròr°rÞryrzÚ cache_len½sz9ParserElement._UnboundedCache.__init__..cache_len)rÑrÜÚtypesÚ MethodTyperìrßr!r)r§rìrßr!râryrÚrzr©°s    z&ParserElement._UnboundedCache.__init__N©r—r˜r™r©ryryryrzÚ_UnboundedCache¯sræNc@seZdZdd„ZdS)úParserElement._FifoCachecs‚tƒ|_‰tƒ‰‡‡fdd„}‡‡fdd„}‡fdd„}‡fdd„}t ||¡|_t ||¡|_t ||¡|_t ||¡|_dS) Ncs ˆ |ˆ¡Sr‰rØrÙrÚryrzrìÌsú.ParserElement._FifoCache.__init__..getcs>|ˆ|<tˆƒˆkr:zˆ d¡Wqtk r6YqXqdS©NF)ròÚpopitemrärÝ)rÛÚsizeryrzrßÏs  ú.ParserElement._FifoCache.__init__..setcs ˆ ¡dSr‰ràr°rÞryrzr!×sú0ParserElement._FifoCache.__init__..clearcstˆƒSr‰rár°rÞryrzrâÚsú4ParserElement._FifoCache.__init__..cache_len) rÑrÜÚ _OrderedDictrãrärìrßr!r©r§rërìrßr!râry)rÛrÜrërzr©Çs   ú!ParserElement._FifoCache.__init__NråryryryrzÚ _FifoCacheÆsròc@seZdZdd„ZdS)rçcs�tƒ|_‰i‰t gˆ¡‰‡‡fdd„}‡‡‡fdd„}‡‡fdd„}‡fdd„}t ||¡|_t ||¡|_t ||¡|_t ||¡|_ dS) Ncs ˆ |ˆ¡Sr‰rØrÙrÚryrzrìêsrècs4|ˆ|<tˆƒˆkr&ˆ ˆ ¡d¡qˆ |¡dSr‰)ròrÚpopleftrrÝ)rÛÚkey_fiforëryrzrßís rìcsˆ ¡ˆ ¡dSr‰ràr°)rÛrôryrzr!ósrícstˆƒSr‰rár°rÞryrzrâ÷srî) rÑrÜÚ collectionsÚdequerãrärìrßr!rrðry)rÛrôrÜrërzr©äs   rñNråryryryrzròãsrc Csd\}}|||||f}tj�îtj}| |¡} | |jkrÆtj|d7<z| ||||¡} Wn8tk r–} z| || j | j Ž¡‚W5d} ~ XYn.X| || d| d  ¡f¡| W5QR£Sn@tj|d7<t | t ƒræ| ‚| d| d  ¡fW5QR£SW5QRXdS)Nr(r�r)r&Úpackrat_cache_lockÚ packrat_cacherìrÜÚpackrat_cache_statsrÔrrßr€r¦rãr}rƒ) r§rbr¢r®r¯ÚHITÚMISSÚlookuprÛrür«ryryrzÚ _parseCaches$   zParserElement._parseCachecCs(tj ¡dgttjƒtjdd…<dSrÍ)r&rør!ròrùryryryrzÚ resetCaches zParserElement.resetCacheé€cCs8tjs4dt_|dkr t ¡t_n t |¡t_tjt_dS)a–Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default=C{128}) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method C{ParserElement.enablePackrat()}. If your program uses C{psyco} to "compile as you go", you must call C{enablePackrat} before calling C{psyco.full()}. If you do not do this, Python will crash. For best results, call C{enablePackrat()} immediately after importing pyparsing. Example:: import pyparsing pyparsing.ParserElement.enablePackrat() TN)r&Ú_packratEnabledrærøròrýr´)Úcache_size_limitryryrzÚ enablePackrat%s   zParserElement.enablePackratc Cs®t ¡|js| ¡|jD] }| ¡q|js8| ¡}z<| |d¡\}}|rr| ||¡}t ƒt ƒ}| ||¡Wn0t k r¤}ztj r�‚n|‚W5d}~XYnX|SdS)aC Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be successfully parsed, then set C{parseAll} to True (equivalent to ending the grammar with C{L{StringEnd()}}). Note: C{parseString} implicitly calls C{expandtabs()} on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the C{loc} argument to index into the string being parsed, you can ensure you have a consistent view of the input string by: - calling C{parseWithTabs} on your grammar before calling C{parseString} (see L{I{parseWithTabs}}) - define your parse action using the full C{(s,loc,toks)} signature, and reference the input string using the parse action's C{s} argument - explicitly expand the tabs in your input string before calling C{parseString} Example:: Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text rN) r&rþršÚ streamliner˜r—Ú expandtabsr´rÊrr+rÚverbose_stacktrace)r§rbÚparseAllrÄr¢rÒÚseriryryrzÚ parseStringHs$    zParserElement.parseStringc cs6|js| ¡|jD] }| ¡q|js4t|ƒ ¡}t|ƒ}d}|j}|j}t   ¡d} z¤||krú| |krúz |||ƒ} ||| dd�\} } Wnt k r¦| d}YqZX| |krð| d7} | | | fV|rê|||ƒ} | |krà| }qî|d7}qø| }qZ| d}qZWn4t k �r0}zt j �r‚n|‚W5d}~XYnXdS)a† Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after 'n' matches are found. If C{overlap} is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}} for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens,start,end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd rF©r¯r�N)ršrr˜r—rˆrròrÊr´r&rþr!rr)r§rbÚ maxMatchesÚoverlaprÄrÉr¢Ú preparseFnÚparseFnÚmatchesrÑÚnextLocrÒÚnextlocriryryrzÚ scanStringzsB       zParserElement.scanStringc Csàg}d}d|_zœ| |¡D]Z\}}}| |||…¡|rpt|tƒrR|| ¡7}nt|tƒrf||7}n | |¡|}q| ||d…¡dd„|Dƒ}d tt t |ƒƒ¡WSt k rÚ}zt j rÆ‚n|‚W5d}~XYnXdS)af Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. rTNcSsg|] }|r|‘qSryry)rŠÚoryryrzrêãsz1ParserElement.transformString..rœ)r—rrr}r$rÖrÝrµr¶rˆÚ_flattenrr&r)r§rbr8ÚlastErxr�rÄriryryrzr…Ás(    zParserElement.transformStringc CsRztdd„| ||¡DƒƒWStk rL}ztjr8‚n|‚W5d}~XYnXdS)a­ Another extension to C{L{scanString}}, simplifying the access to the tokens found to match the given parse expression. May be called with optional C{maxMatches} argument, to clip searching after 'n' matches are found. Example:: # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters cap_word = Word(alphas.upper(), alphas.lower()) print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) # the sum() builtin can be used to merge results into a single ParseResults object print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))) prints:: [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] cSsg|]\}}}|‘qSryry)rŠrxr�rÄryryrzrêÿsz.ParserElement.searchString..N)r$rrr&r)r§rbr riryryrzÚ searchStringìs zParserElement.searchStringc csTd}d}|j||d�D]*\}}}|||…V|r<|dV|}q||d…VdS)a[ Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] r)r N)r) r§rbÚmaxsplitÚincludeSeparatorsZsplitsÚlastrxr�rÄryryrzr‘s  zParserElement.splitcCsFt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dSt||gƒS)a– Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!'] ú4Cannot combine element of type %s with ParserElementrs©Ú stacklevelN) r}râr&rŒÚwarningsÚwarnr¼Ú SyntaxWarningrr0ryryrzr%s   ÿzParserElement.__add__cCsBt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dS||S)z] Implementation of + operator when left operand is not a C{L{ParserElement}} rrsrN©r}râr&rŒrrr¼rr0ryryrzr11s   ÿzParserElement.__radd__cCsJt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dS|t  ¡|S)zQ Implementation of - operator, returns C{L{And}} with error stop rrsrN) r}râr&rŒrrr¼rrÚ _ErrorStopr0ryryrzÚ__sub__=s   ÿzParserElement.__sub__cCsBt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dS||S)z] Implementation of - operator when left operand is not a C{L{ParserElement}} rrsrNrr0ryryrzÚ__rsub__Is   ÿzParserElement.__rsub__cs¸t|tƒr|d}}nät|tƒrì|ddd…}|ddkrHd|df}t|dtƒr |ddkr |ddkrvtˆƒS|ddkrŠtˆƒSˆ|dtˆƒSqút|dtƒrÎt|dtƒrÎ|\}}||8}qútdt|dƒt|dƒƒ‚ntdt|ƒƒ‚|dk�r tdƒ‚|dk�rtd ƒ‚||k�r6dk�rBnntd ƒ‚|�r–‡‡fd d „‰|�rŒ|dk�rtˆˆ|ƒ}ntˆg|ƒˆ|ƒ}nˆ|ƒ}n|dk�r¦ˆ}ntˆg|ƒ}|S) aå Implementation of * operator, allows use of C{expr * 3} in place of C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples may also include C{None} as in: - C{expr*(n,None)} or C{expr*(n,)} is equivalent to C{expr*n + L{ZeroOrMore}(expr)} (read as "at least n instances of C{expr}") - C{expr*(None,n)} is equivalent to C{expr*(0,n)} (read as "0 to n instances of C{expr}") - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} Note that C{expr*(None,n)} does not raise an exception if more than n exprs exist in the input stream; that is, C{expr*(None,n)} does not enforce a maximum number of expr occurrences. If this behavior is desired, then write C{expr*(None,n) + ~expr} r)NNNrsr�z7cannot multiply 'ParserElement' and ('%s','%s') objectsz0cannot multiply 'ParserElement' and '%s' objectsz/cannot multiply ParserElement by negative valuez@second tuple value must be greater or equal to first tuple valuez+cannot multiply ParserElement by 0 or (0,0)cs(|dkrtˆˆ|dƒƒStˆƒSdSrÇ)r©Ún©ÚmakeOptionalListr§ryrzr&†sz/ParserElement.__mul__..makeOptionalList) r}rvÚtupler4rrår¼Ú ValueErrorr)r§r$Ú minElementsÚ optElementsr‡ryr%rzÚ__mul__UsD             zParserElement.__mul__cCs | |¡Sr‰)r+r0ryryrzÚ__rmul__™szParserElement.__rmul__cCsFt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dSt||gƒS)zI Implementation of | operator - returns C{L{MatchFirst}} rrsrN) r}râr&rŒrrr¼rrr0ryryrzÚ__or__œs   ÿzParserElement.__or__cCsBt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dS||BS)z] Implementation of | operator when left operand is not a C{L{ParserElement}} rrsrNrr0ryryrzÚ__ror__¨s   ÿzParserElement.__ror__cCsFt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dSt||gƒS)zA Implementation of ^ operator - returns C{L{Or}} rrsrN) r}râr&rŒrrr¼rrr0ryryrzÚ__xor__´s   ÿzParserElement.__xor__cCsBt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dS||AS)z] Implementation of ^ operator when left operand is not a C{L{ParserElement}} rrsrNrr0ryryrzÚ__rxor__Às   ÿzParserElement.__rxor__cCsFt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dSt||gƒS)zC Implementation of & operator - returns C{L{Each}} rrsrN) r}râr&rŒrrr¼rrr0ryryrzÚ__and__Ìs   ÿzParserElement.__and__cCsBt|tƒrt |¡}t|tƒs:tjdt|ƒtdd�dS||@S)z] Implementation of & operator when left operand is not a C{L{ParserElement}} rrsrNrr0ryryrzÚ__rand__Øs   ÿzParserElement.__rand__cCst|ƒS)zE Implementation of ~ operator - returns C{L{NotAny}} )rr°ryryrzÚ __invert__äszParserElement.__invert__cCs|dk r| |¡S| ¡SdS)a  Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") N)r«rãr"ryryrzÚ__call__ês zParserElement.__call__cCst|ƒS)zˆ Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output. )r-r°ryryrzÚsuppressýszParserElement.suppresscCs d|_|S)a Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. F©r“r°ryryrzÚleaveWhitespaceszParserElement.leaveWhitespacecCsd|_||_d|_|S)z8 Overrides the default whitespace chars TF)r“r”r•)r§rŠryryrzÚsetWhitespaceChars sz ParserElement.setWhitespaceCharscCs d|_|S)zé Overrides default behavior to expand C{}s to spaces before parsing the input string. Must be called before C{parseString} when the input grammar contains elements that match C{} characters. T)r—r°ryryrzÚ parseWithTabsszParserElement.parseWithTabscCsLt|tƒrt|ƒ}t|tƒr4||jkrH|j |¡n|j t| ¡ƒ¡|S)a× Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(cStyleComment) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] )r}râr-r˜rrãr0ryryrzÚignores   zParserElement.ignorecCs"|pt|p t|ptf|_d|_|S)zT Enable display of debugging messages while doing pattern matching. T)rdrhrjržr™)r§Z startActionZ successActionZexceptionActionryryrzÚsetDebugActions6s þzParserElement.setDebugActionscCs|r| ttt¡nd|_|S)aŽ Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using L{setDebugActions}. Prior to attempting to match the C{wd} expression, the debugging message C{"Match at loc (,)"} is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. F)r;rdrhrjr™)r§ÚflagryryrzÚsetDebug@s#zParserElement.setDebugcCs|jSr‰)rÕr°ryryrzr±iszParserElement.__str__cCst|ƒSr‰r²r°ryryrzr³lszParserElement.__repr__cCsd|_d|_|SrÐ)ršr�r°ryryrzroszParserElement.streamlinecCsdSr‰ryrÃryryrzÚcheckRecursiontszParserElement.checkRecursioncCs| g¡dS)zj Check defined expressions for valid structure, check for infinite recursive definitions. N)r>)r§Ú validateTraceryryrzÚvalidatewszParserElement.validatec Cs„z | ¡}Wn2tk r>t|dƒ�}| ¡}W5QRXYnXz| ||¡WStk r~}ztjrj‚n|‚W5d}~XYnXdS)zÐ Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. ÚrN)Úreadr®Úopenrrr&r)r§Úfile_or_filenamerÚ file_contentsÚfriryryrzÚ parseFile}s  zParserElement.parseFilecsHt|tƒr"||kp t|ƒt|ƒkSt|tƒr6| |¡Stt|ƒ|kSdSr‰)r}r&ÚvarsrârÚsuperr0©r€ryrzÚ__eq__‘s    zParserElement.__eq__cCs ||k Sr‰ryr0ryryrzÚ__ne__™szParserElement.__ne__cCs tt|ƒƒSr‰)ÚhashÚidr°ryryrzÚ__hash__œszParserElement.__hash__cCs||kSr‰ryr0ryryrzÚ__req__ŸszParserElement.__req__cCs ||k Sr‰ryr0ryryrzÚ__rne__¢szParserElement.__rne__cCs4z|jt|ƒ|d�WdStk r.YdSXdS)aÓ Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - testString - to test against this expression for a match - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests Example:: expr = Word(nums) assert expr.matches("100") ©rTFN)rrˆr)r§Z testStringrryryrzr¥s zParserElement.matchesú#c Csòt|tƒr"tttj| ¡ ¡ƒƒ}t|tƒr4t|ƒ}g}g}d} |D�]¢} |dk r^|  | d¡sf|rr| sr|  | ¡qD| sxqDd  |¡| g} g}z:|   dd¡} |j | |d�} |   | j|d�¡| oÀ| } Wnðtk �rr} zŽt| tƒrædnd }d| k�r*|   t| j| ƒ¡|   d t| j| ƒd d |¡n|   d | jd |¡|   d t| ƒ¡| �o\|} | } W5d} ~ XYnDtk �r´}z$|   dt|ƒ¡| �ož|} |} W5d}~XYnX|�rÚ|�rÌ|   d ¡td  | ¡ƒ|  | | f¡qD| |fS)a3 Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\n of strings that spans \n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.) TNFr@ú\nrR)rSz(FATAL)rœú r�ú^zFAIL: zFAIL-EXCEPTION: )r}rârÝr¶rr¶ÚrstripÚ splitlinesrrrrµr“rrPrr#rIr¢r;rƒra)r§ÚtestsrÚcommentÚfullDumpÚ printResultsÚ failureTestsÚ allResultsÚcommentsÚsuccessrxr8Úresultr«r»riryryrzÚrunTests¸sNW      $   zParserElement.runTests)F)F)T)T)TT)TT)rÿ)F)N)T)F)T)TrSTTF)Or—r˜r™r¾rˆrÚ staticmethodr‹r�r©rãr¦r«rµr„r¹rÀrÁrÆrÊrÌrÏrÔrÖr×rÑrærïròrørr÷rùrýr´rþrrrÚ_MAX_INTrr…rr‘r%r1r!r"r+r,r-r.r/r0r1r2r3r4r5r7r8r9r:r;r=r±r³rr>r@rGrKrLrOrPrQrrbÚ __classcell__ryryrJrzr&Os˜     &     G   " 2G+    D           )    cs eZdZdZ‡fdd„Z‡ZS)r.zT Abstract C{ParserElement} subclass, for defining atomic matching patterns. cstt|ƒjdd�dS©NF©r¢)rIr.r©r°rJryrzr©@ szToken.__init__©r—r˜r™r¾r©reryryrJrzr.< scs eZdZdZ‡fdd„Z‡ZS)rz, An empty token, will always match. cs$tt|ƒ ¡d|_d|_d|_dS)NrTF)rIrr©rÕr–r›r°rJryrzr©H szEmpty.__init__rhryryrJrzrD scs*eZdZdZ‡fdd„Zddd„Z‡ZS)rz( A token that will never match. cs*tt|ƒ ¡d|_d|_d|_d|_dS)NrTFzUnmatchable token)rIrr©rÕr–r›rœr°rJryrzr©S s zNoMatch.__init__TcCst|||j|ƒ‚dSr‰)r!rœrËryryrzrÌZ szNoMatch.parseImpl)T©r—r˜r™r¾r©rÌreryryrJrzrO s cs*eZdZdZ‡fdd„Zddd„Z‡ZS)raÐ Token to exactly match a specified string. Example:: Literal('blah').parseString('blah') # -> ['blah'] Literal('blah').parseString('blahfooblah') # -> ['blah'] Literal('blah').parseString('bla') # -> Exception: Expected "blah" For case-insensitive matching, use L{CaselessLiteral}. For keyword matching (force word break before and after the matched string), use L{Keyword} or L{CaselessKeyword}. cs„tt|ƒ ¡||_t|ƒ|_z|d|_Wn*tk rVtj dt dd�t |_ YnXdt |jƒ|_d|j|_d|_d|_dS)Nrz2null string passed to Literal; use Empty() insteadrsrú"%s"r¤F)rIrr©ÚmatchròÚmatchLenÚfirstMatchCharrærrrrr€rˆrÕrœr–r›©r§Ú matchStringrJryrzr©l s ÿ  zLiteral.__init__TcCsJ|||jkr6|jdks&| |j|¡r6||j|jfSt|||j|ƒ‚dSrÇ)rmrlÚ startswithrkr!rœrËryryrzrÌ sÿ ÿzLiteral.parseImpl)TriryryrJrzr^ s csLeZdZdZedZd‡fdd„ Zddd „Z‡fd d „Ze d d „ƒZ ‡Z S)ra\ Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with C{L{Literal}}: - C{Literal("if")} will match the leading C{'if'} in C{'ifAndOnlyIf'}. - C{Keyword("if")} will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'} Accepts two optional constructor arguments in addition to the keyword string: - C{identChars} is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + "_" and "$" - C{caseless} allows case-insensitive matching, default is C{False}. Example:: Keyword("start").parseString("start") # -> ['start'] Keyword("start").parseString("starting") # -> Exception For case-insensitive matching, use L{CaselessKeyword}. ú_$NFcs®tt|ƒ ¡|dkrtj}||_t|ƒ|_z|d|_Wn$tk r^t j dt dd�YnXd|j|_ d|j |_ d|_d|_||_|r | ¡|_| ¡}t|ƒ|_dS)Nrz2null string passed to Keyword; use Empty() insteadrsrrjr¤F)rIrr©ÚDEFAULT_KEYWORD_CHARSrkròrlrmrærrrrÕrœr–r›ÚcaselessÚupperÚ caselessmatchrßÚ identChars)r§rorvrsrJryrzr©š s* ÿ    zKeyword.__init__TcCs|jr|||||j… ¡|jkrò|t|ƒ|jksL|||j ¡|jkrò|dksj||d ¡|jkrò||j|jfSnv|||jkrò|jdks¢| |j|¡rò|t|ƒ|jksÈ|||j|jkrò|dksâ||d|jkrò||j|jfSt |||j |ƒ‚dSrñ) rsrlrtruròrvrkrmrpr!rœrËryryrzr̯ s4ÿÿþþÿ ÿþþýýzKeyword.parseImplcstt|ƒ ¡}tj|_|Sr‰)rIrrãrrrv)r§r rJryrzrã½ sz Keyword.copycCs |t_dS)z,Overrides the default Keyword chars N)rrrr‰ryryrzÚsetDefaultKeywordChars szKeyword.setDefaultKeywordChars)NF)T) r—r˜r™r¾r5rrr©rÌrãrcrwreryryrJrzr‡ s  cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r al Token to match a specified string, ignoring case of letters. Note: the matched results will always be in the case of the given match string, NOT the case of the input text. Example:: OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] (Contrast with example for L{CaselessKeyword}.) cs6tt|ƒ | ¡¡||_d|j|_d|j|_dS)Nz'%s'r¤)rIr r©rtÚ returnStringrÕrœrnrJryrzr©Ó s zCaselessLiteral.__init__TcCs@||||j… ¡|jkr,||j|jfSt|||j|ƒ‚dSr‰)rlrtrkrxr!rœrËryryrzrÌÚ szCaselessLiteral.parseImpl)TriryryrJrzr È s cs,eZdZdZd‡fdd„ Zd dd„Z‡ZS) r zÐ Caseless version of L{Keyword}. Example:: OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD'] (Contrast with example for L{CaselessLiteral}.) Ncstt|ƒj||dd�dS)NT©rs)rIr r©)r§rorvrJryrzr©è szCaselessKeyword.__init__TcCsj||||j… ¡|jkrV|t|ƒ|jksF|||j ¡|jkrV||j|jfSt|||j|ƒ‚dSr‰)rlrtruròrvrkr!rœrËryryrzrÌë sÿÿzCaselessKeyword.parseImpl)N)TriryryrJrzr ß scs,eZdZdZd‡fdd„ Zd dd„Z‡ZS) rnax A variation on L{Literal} which matches "close" matches, that is, strings with at most 'n' mismatching characters. C{CloseMatch} takes parameters: - C{match_string} - string to be matched - C{maxMismatches} - (C{default=1}) maximum number of mismatches allowed to count as a match The results from a successful parse will contain the matched text from the input string and the following named results: - C{mismatches} - a list of the positions within the match_string where mismatches were found - C{original} - the original match_string used to compare against the input string If C{mismatches} is an empty list, then the match was an exact match. Example:: patt = CloseMatch("ATCATCGAATGGA") patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) # exact match patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) # close match allowing up to 2 mismatches patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2) patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) r�csBtt|ƒ ¡||_||_||_d|j|jf|_d|_d|_dS)Nz&Expected %r (with up to %d mismatches)F) rIrnr©rÕÚ match_stringÚ maxMismatchesrœr›r–)r§rzr{rJryrzr© szCloseMatch.__init__TcCsÊ|}t|ƒ}|t|jƒ}||kr¶|j}d}g} |j} tt|||…|jƒƒD]2\}} | \} } | | krN|  |¡t| ƒ| krNq¶qN|d}t|||…gƒ}|j|d<| |d<||fSt|||j|ƒ‚dS)Nrr�ÚoriginalÚ mismatches) ròrzr{r÷r’rr$r!rœ)r§rbr¢r®ÚstartrÉÚmaxlocrzÚmatch_stringlocr}r{Ús_mÚsrcÚmatÚresultsryryrzrÌ s(    zCloseMatch.parseImpl)r�)TriryryrJrzrnñ s cs8eZdZdZd ‡fdd„ Zdd d „Z‡fd d „Z‡ZS)r1a Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction. An optional C{excludeChars} parameter can list characters that might be found in the input C{bodyChars} string; useful to define a word of all printables except for one or two characters, for instance. L{srange} is useful for defining custom character set strings for defining C{Word} expressions, using range notation from regular expression character sets. A common mistake is to use C{Word} to match a specific literal string, as in C{Word("Address")}. Remember that C{Word} uses the string argument to define I{sets} of matchable characters. This expression would match "Add", "AAA", "dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an exact literal string, use L{Literal} or L{Keyword}. pyparsing includes helper strings for building Words: - L{alphas} - L{nums} - L{alphanums} - L{hexnums} - L{alphas8bit} (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.) - L{punc8bit} (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.) - L{printables} (any non-whitespace character) Example:: # a word composed of digits integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9")) # a word with a leading capital, and zero or more lowercase capital_word = Word(alphas.upper(), alphas.lower()) # hostnames are alphanumeric, with leading alpha, and '-' hostname = Word(alphas, alphanums+'-') # roman numeral (not a strict parser, accepts invalid mix of characters) roman = Word("IVXLCDM") # any string of non-whitespace characters, except for ',' csv_value = Word(printables, excludeChars=",") Nr�rFcsÌtt|ƒ ¡ˆrFd ‡fdd„|Dƒ¡}|rFd ‡fdd„|Dƒ¡}||_t|ƒ|_|rl||_t|ƒ|_n||_t|ƒ|_|dk|_ |dkr–t dƒ‚||_ |dkr¬||_ nt |_ |dkrÆ||_ ||_ t|ƒ|_d|j|_d |_||_d |j|jk�rÈ|dk�rÈ|dk�rÈ|dk�rÈ|j|jk�r8d t|jƒ|_nHt|jƒdk�rfd t |j¡t|jƒf|_nd t|jƒt|jƒf|_|j�r˜d|jd|_zt |j¡|_Wntk �rÆd|_YnXdS)Nrœc3s|]}|ˆkr|VqdSr‰ryrŸ©Ú excludeCharsryrzrŒ` sz Word.__init__..c3s|]}|ˆkr|VqdSr‰ryrŸr…ryrzrŒb srr�zZcannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permittedr¤FrUz[%s]+z%s[%s]*z [%s][%s]*z\b)rIr1r©rµÚ initCharsOrigrßÚ initCharsÚ bodyCharsOrigÚ bodyCharsÚ maxSpecifiedr(ÚminLenÚmaxLenrdrˆrÕrœr›Ú asKeywordÚ_escapeRegexRangeCharsÚreStringròrŸÚescapeÚcompilerƒ)r§rˆrŠÚminÚmaxÚexactrŽr†rJr…rzr©] s\      0 ÿÿÿÿz Word.__init__Tc Cs>|jr<|j ||¡}|s(t|||j|ƒ‚| ¡}|| ¡fS|||jkrZt|||j|ƒ‚|}|d7}t|ƒ}|j}||j }t ||ƒ}||kr¦|||kr¦|d7}qˆd} |||j kr¼d} |j rÚ||krÚ|||krÚd} |j �r|dkrü||d|k�s||k�r|||k�rd} | �r.t|||j|ƒ‚||||…fS)Nr�FTr)rŸrkr!rœÚendÚgrouprˆròrŠr�r“rŒr‹rŽ) r§rbr¢r®rar~rÉÚ bodycharsrÚthrowExceptionryryrzrÌ“ s6    2zWord.parseImplcsvztt|ƒ ¡WStk r$YnX|jdkrpdd„}|j|jkr`d||jƒ||jƒf|_nd||jƒ|_|jS)NcSs$t|ƒdkr|dd…dS|SdS)Néú...rá©r�ryryrzÚ charsAsStr¿ s z Word.__str__..charsAsStrz W:(%s,%s)zW:(%s))rIr1r±rƒr�r‡r‰)r§r�rJryrzr±¶ s  z Word.__str__)Nr�rrFN)T©r—r˜r™r¾r©rÌr±reryryrJrzr1. s.6 #csFeZdZdZee d¡ƒZd ‡fdd„ Zd dd„Z ‡fd d „Z ‡Z S) r)a� Token for matching strings that match a given regular expression. Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module. If the given regex contains named groups (defined using C{(?P...)}), these will be preserved as named parse results. Example:: realnum = Regex(r"[+-]?\d+\.\d*") date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') # ref: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression roman = Regex(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") z[A-Z]rcsÞtt|ƒ ¡t|tƒr†|s,tjdtdd�||_||_ zt   |j|j ¡|_ |j|_ Wq¸t jk r‚tjd|tdd�‚Yq¸Xn2t|tjƒr°||_ t|ƒ|_|_ ||_ ntdƒ‚t|ƒ|_d|j|_d|_d|_d S) z­The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.z0null string passed to Regex; use Empty() insteadrsrú$invalid pattern (%s) passed to RegexzCRegex may only be constructed with a string or a compiled RE objectr¤FTN)rIr)r©r}rârrrÚpatternÚflagsrŸr’r�Ú sre_constantsÚerrorÚcompiledREtyperr(rˆrÕrœr›r–)r§r r¡rJryrzr©Û s: ÿ  ÿ  ÿ  zRegex.__init__TcCs`|j ||¡}|s"t|||j|ƒ‚| ¡}| ¡}t| ¡ƒ}|rX|D]}||||<qF||fSr‰)rŸrkr!rœr–Ú groupdictr$r—)r§rbr¢r®raÚdr‡rîryryrzrÌý s zRegex.parseImplcsFztt|ƒ ¡WStk r$YnX|jdkr@dt|jƒ|_|jS)NzRe:(%s))rIr)r±rƒr�rÎr r°rJryrzr± s z Regex.__str__)r)T) r—r˜r™r¾r¼rŸr’r¤r©rÌr±reryryrJrzr)Í s  " cs8eZdZdZd ‡fdd„ Zd dd„Z‡fd d „Z‡ZS) r'a« Token for matching strings that are delimited by quoting characters. Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default=C{None}) - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=C{None}) - multiline - boolean indicating whether quotes can span multiple lines (default=C{False}) - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True}) - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar) - convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True}) Example:: qs = QuotedString('"') print(qs.searchString('lsjdf "This is the quote" sldjf')) complex_qs = QuotedString('{{', endQuoteChar='}}') print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf')) sql_qs = QuotedString('"', escQuote='""') print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf')) prints:: [['This is the quote']] [['This is the "quote"']] [['This is the quote with "embedded" quotes']] NFTc sNttˆƒ ¡| ¡}|s0tjdtdd�tƒ‚|dkr>|}n"| ¡}|s`tjdtdd�tƒ‚|ˆ_t |ƒˆ_ |dˆ_ |ˆ_ t |ƒˆ_ |ˆ_|ˆ_|ˆ_|ˆ_|rètjtjBˆ_dt ˆj¡tˆj dƒ|dk rÜt|ƒpÞdfˆ_n.rtú)z|(?:%s)z|(?:%s.)z(.)z)*%srŸr¤FT)%rIr'r©r¶rrrÚ SyntaxErrorÚ quoteCharròÚ quoteCharLenÚfirstQuoteCharr§ÚendQuoteCharLenÚescCharÚescQuoteÚunquoteResultsÚconvertWhitespaceEscapesrŸÚ MULTILINEÚDOTALLr¡r‘r�r rµróÚescCharReplacePatternr’r�r¢r£rˆrÕrœr›r–)r§rªr®r¯Ú multiliner°r§r±rJr°rzr©/ s|     þÿ  þÿþþÿ  ÿ  zQuotedString.__init__c CsÔ|||jkr|j ||¡pd}|s4t|||j|ƒ‚| ¡}| ¡}|jrÌ||j|j …}t |t ƒrÌd|kr |j r dddddœ}|  ¡D]\}}| ||¡}qŠ|jr¶t |jd|¡}|jrÌ| |j|j¡}||fS)Nú\ú r@ú ú )ú\trTz\fz\rz\g<1>)r¬rŸrkr!rœr–r—r°r«r­r}râr±rör“r®rïr´r¯r§) r§rbr¢r®rar‡Úws_mapÚwslitÚwscharryryrzrÌp s*  üzQuotedString.parseImplcsHztt|ƒ ¡WStk r$YnX|jdkrBd|j|jf|_|jS)Nz.quoted string, starting with %s ending with %s)rIr'r±rƒr�rªr§r°rJryrzr±“ s zQuotedString.__str__)NNFTNT)TržryryrJrzr' sA #cs8eZdZdZd ‡fdd„ Zd dd„Z‡fd d „Z‡ZS) r aô Token for matching words composed of characters I{not} in a given set (will include whitespace in matched characters if not listed in the provided exclusion set - see example). Defined with string containing all disallowed characters, and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction. Example:: # define a comma-separated-value as anything that is not a ',' csv_value = CharsNotIn(',') print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213")) prints:: ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] r�rcs†tt|ƒ ¡d|_||_|dkr*tdƒ‚||_|dkr@||_nt|_|dkrZ||_||_t |ƒ|_ d|j |_ |jdk|_ d|_ dS)NFr�zfcannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permittedrr¤)rIr r©r“ÚnotCharsr(rŒr�rdrˆrÕrœr–r›)r§r¾r“r”r•rJryrzr©¯ s    zCharsNotIn.__init__TcCs�|||jkrt|||j|ƒ‚|}|d7}|j}t||jt|ƒƒ}||krb|||krb|d7}qD|||jkr€t|||j|ƒ‚||||…fSrÇ)r¾r!rœr“r�ròrŒ)r§rbr¢r®r~ÚnotcharsÚmaxlenryryrzrÌÇ s ÿ zCharsNotIn.parseImplcsfztt|ƒ ¡WStk r$YnX|jdkr`t|jƒdkrTd|jdd…|_n d|j|_|jS)Nršz !W:(%s...)z!W:(%s))rIr r±rƒr�ròr¾r°rJryrzr±Ø s  zCharsNotIn.__str__)r�rr)TržryryrJrzr Ÿ s cs<eZdZdZddddddœZd‡fd d „ Zddd„Z‡ZS)r0a� Special matching class for matching whitespace. Normally, whitespace is ignored by pyparsing grammars. This class is included when some whitespace structures are significant. Define with a string containing the whitespace characters to be matched; default is C{" \t\r\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments, as defined for the C{L{Word}} class. zzzzz)rUr·r@r¹r¸ú r�rcs’ttˆƒ ¡|ˆ_ˆ d ‡fdd„ˆjDƒ¡¡d dd„ˆjDƒ¡ˆ_dˆ_dˆjˆ_ |ˆ_ |dkrt|ˆ_ nt ˆ_ |dkrŽ|ˆ_ |ˆ_ dS)Nrœc3s|]}|ˆjkr|VqdSr‰)Ú matchWhiterŸr°ryrzrŒø s z!White.__init__..css|]}tj|VqdSr‰)r0Ú whiteStrsrŸryryrzrŒú sTr¤r) rIr0r©rÂr8rµr”rÕr–rœrŒr�rd)r§Úwsr“r”r•rJr°rzr©õ s  zWhite.__init__TcCs�|||jkrt|||j|ƒ‚|}|d7}||j}t|t|ƒƒ}||krb|||jkrb|d7}qB|||jkr€t|||j|ƒ‚||||…fSrÇ)rÂr!rœr�r“ròrŒ)r§rbr¢r®r~rryryrzrÌ s  zWhite.parseImpl)rÁr�rr)T)r—r˜r™r¾rÃr©rÌreryryrJrzr0æ sûcseZdZ‡fdd„Z‡ZS)Ú_PositionTokencs(tt|ƒ ¡|jj|_d|_d|_dSrÂ)rIrÅr©r€r—rÕr–r›r°rJryrzr© s z_PositionToken.__init__©r—r˜r™r©reryryrJrzrÅ srÅcs2eZdZdZ‡fdd„Zdd„Zd dd„Z‡ZS) rzb Token to advance to a specific column of input text; useful for tabular report scraping. cstt|ƒ ¡||_dSr‰)rIrr©r;)r§ÚcolnorJryrzr©$ szGoToColumn.__init__cCs\t||ƒ|jkrXt|ƒ}|jr*| ||¡}||krX|| ¡rXt||ƒ|jkrX|d7}q*|SrÇ)r;ròr˜rÆÚisspace)r§rbr¢rÉryryrzrÊ( s $ zGoToColumn.preParseTcCsDt||ƒ}||jkr"t||d|ƒ‚||j|}|||…}||fS)NzText not in expected column©r;r!)r§rbr¢r®ÚthiscolÚnewlocr‡ryryrzrÌ1 s    zGoToColumn.parseImpl)T)r—r˜r™r¾r©rÊrÌreryryrJrzr s  cs*eZdZdZ‡fdd„Zddd„Z‡ZS)ra¿ Matches if current position is at the beginning of a line within the parse string Example:: test = ''' AAA this line AAA and this line AAA but not this one B AAA and definitely not this one ''' for t in (LineStart() + 'AAA' + restOfLine).searchString(test): print(t) Prints:: ['AAA', ' this line'] ['AAA', ' and this line'] cstt|ƒ ¡d|_dS)NzExpected start of line)rIrr©rœr°rJryrzr©O szLineStart.__init__TcCs*t||ƒdkr|gfSt|||j|ƒ‚dSrÇ)r;r!rœrËryryrzrÌS szLineStart.parseImpl)TriryryrJrzr: s cs*eZdZdZ‡fdd„Zddd„Z‡ZS)rzU Matches if current position is at the end of a line within the parse string cs,tt|ƒ ¡| tj dd¡¡d|_dS)Nr@rœzExpected end of line)rIrr©r8r&rˆr“rœr°rJryrzr©\ szLineEnd.__init__TcCsb|t|ƒkr6||dkr$|ddfSt|||j|ƒ‚n(|t|ƒkrN|dgfSt|||j|ƒ‚dS)Nr@r�©ròr!rœrËryryrzrÌa s     zLineEnd.parseImpl)TriryryrJrzrX s cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r,zM Matches if current position is at the beginning of the parse string cstt|ƒ ¡d|_dS)NzExpected start of text)rIr,r©rœr°rJryrzr©p szStringStart.__init__TcCs0|dkr(|| |d¡kr(t|||j|ƒ‚|gfSrÍ)rÊr!rœrËryryrzrÌt szStringStart.parseImpl)TriryryrJrzr,l s cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r+zG Matches if current position is at the end of the parse string cstt|ƒ ¡d|_dS)NzExpected end of text)rIr+r©rœr°rJryrzr© szStringEnd.__init__TcCs^|t|ƒkrt|||j|ƒ‚n<|t|ƒkr6|dgfS|t|ƒkrJ|gfSt|||j|ƒ‚dSrÇrÌrËryryrzr̃ s    zStringEnd.parseImpl)TriryryrJrzr+{ s cs.eZdZdZef‡fdd„ Zddd„Z‡ZS)r3ap Matches if the current position is at the beginning of a Word, and is not preceded by any character in a given set of C{wordChars} (default=C{printables}). To emulate the C{} behavior of regular expressions, use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of the string being parsed, or at the beginning of a line. cs"tt|ƒ ¡t|ƒ|_d|_dS)NzNot at the start of a word)rIr3r©rßÚ wordCharsrœ©r§rÍrJryrzr©• s zWordStart.__init__TcCs@|dkr8||d|jks(|||jkr8t|||j|ƒ‚|gfSrñ)rÍr!rœrËryryrzrÌš s  ÿzWordStart.parseImpl)T©r—r˜r™r¾rXr©rÌreryryrJrzr3� scs.eZdZdZef‡fdd„ Zddd„Z‡ZS)r2aZ Matches if the current position is at the end of a Word, and is not followed by any character in a given set of C{wordChars} (default=C{printables}). To emulate the C{} behavior of regular expressions, use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of the string being parsed, or at the end of a line. cs(tt|ƒ ¡t|ƒ|_d|_d|_dS)NFzNot at the end of a word)rIr2r©rßrÍr“rœrÎrJryrzr©© s zWordEnd.__init__TcCsPt|ƒ}|dkrH||krH|||jks8||d|jkrHt|||j|ƒ‚|gfSrñ)ròrÍr!rœ)r§rbr¢r®rÉryryrzr̯ sÿzWordEnd.parseImpl)TrÏryryrJrzr2¡ scs„eZdZdZd‡fdd„ Zdd„Zdd„Zd d „Z‡fd d „Z‡fd d„Z ‡fdd„Z d‡fdd„ Z gfdd„Z ‡fdd„Z ‡ZS)r"z^ Abstract subclass of ParserElement, for combining and post-processing parsed tokens. Fcs®tt|ƒ |¡t|tƒr"t|ƒ}t|tƒr.F)rIr"r©r}rßrÝrâr&rŒÚexprsrÚallr¶rår ©r§rÐr¢rJryrzr©¼ s     zParseExpression.__init__cCs |j|Sr‰)rÐrÊryryrzrÌÐ szParseExpression.__getitem__cCs|j |¡d|_|Sr‰)rÐrr�r0ryryrzrÓ s zParseExpression.appendcCs0d|_dd„|jDƒ|_|jD] }| ¡q|S)z~Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on all contained expressions.FcSsg|] }| ¡‘qSryr#©rŠrÄryryrzrêÜ sz3ParseExpression.leaveWhitespace..)r“rÐr7)r§rÄryryrzr7Ø s   zParseExpression.leaveWhitespacecsrt|tƒrB||jkrntt|ƒ |¡|jD]}| |jd¡q*n,tt|ƒ |¡|jD]}| |jd¡qX|Sr)r}r-r˜rIr"r:rÐ)r§r$rÄrJryrzr:á s    zParseExpression.ignorecsNztt|ƒ ¡WStk r$YnX|jdkrHd|jjt|jƒf|_|jS©Nz%s:(%s)) rIr"r±rƒr�r€r—rˆrÐr°rJryrzr±í s zParseExpression.__str__cs*tt|ƒ ¡|jD] }| ¡qt|jƒdk�r|jd}t||jƒr |js |jdkr |j s |jdd…|jdg|_d|_ |j |j O_ |j |j O_ |jd}t||jƒ�r|j�s|jdk�r|j �s|jdd…|jdd…|_d|_ |j |j O_ |j |j O_ dt |ƒ|_|S)Nrsrr�rtr¤)rIr"rrÐròr}r€rŽr‘r™r�r–r›rˆrœ)r§rÄr$rJryrzr÷ s<    ÿþý ÿþýzParseExpression.streamlinecstt|ƒ ||¡}|Sr‰)rIr"r«)r§rÕr©r‡rJryrzr« szParseExpression.setResultsNamecCs6|dd…|g}|jD]}| |¡q| g¡dSr‰)rÐr@r>)r§r?ÚtmprÄryryrzr@ s  zParseExpression.validatecs$tt|ƒ ¡}dd„|jDƒ|_|S)NcSsg|] }| ¡‘qSryr#rÓryryrzrê% sz(ParseExpression.copy..)rIr"rãrÐr?rJryrzrã# szParseExpression.copy)F)F)r—r˜r™r¾r©rÌrr7r:r±rr«r@rãreryryrJrzr"¸ s " csTeZdZdZGdd„deƒZd‡fdd„ Zddd„Zd d „Zd d „Z d d„Z ‡Z S)ra  Requires all given C{ParseExpression}s to be found in the given order. Expressions may be separated by whitespace. May be constructed using the C{'+'} operator. May also be constructed using the C{'-'} operator, which will suppress backtracking. Example:: integer = Word(nums) name_expr = OneOrMore(Word(alphas)) expr = And([integer("id"),name_expr("name"),integer("age")]) # more easily written as: expr = integer("id") + name_expr("name") + integer("age") cseZdZ‡fdd„Z‡ZS)zAnd._ErrorStopcs&ttj|ƒj||Žd|_| ¡dS)Nú-)rIrr r©rÕr7rVrJryrzr©9 szAnd._ErrorStop.__init__rÆryryrJrzr 8 sr TcsRtt|ƒ ||¡tdd„|jDƒƒ|_| |jdj¡|jdj|_d|_ dS)Ncss|] }|jVqdSr‰©r–rÓryryrzrŒ@ szAnd.__init__..rT) rIrr©rÑrÐr–r8r”r“r rÒrJryrzr©> s z And.__init__c Csþ|jdj|||dd�\}}d}|jdd…D]Æ}t|tjƒrDd}q.|rÎz| |||¡\}}Wqàtk rt‚Yqàtk r¤}zd|_t |¡‚W5d}~XYqàt k rÊt|t |ƒ|j |ƒ‚YqàXn| |||¡\}}|sì|  ¡r.||7}q.||fS)NrFr r�T) rÐr´r}rr r%rÚ __traceback__r¬ræròrœr) r§rbr¢r®Ú resultlistÚ errorStoprÄÚ exprtokensr«ryryrzrÌE s(   z And.parseImplcCst|tƒrt |¡}| |¡Sr‰©r}râr&rŒrr0ryryrzr/^ s  z And.__iadd__cCs6|dd…|g}|jD]}| |¡|jsq2qdSr‰)rÐr>r–©r§rÄÚsubRecCheckListrÄryryrzr>c s   zAnd.checkRecursioncCs@t|dƒr|jS|jdkr:dd dd„|jDƒ¡d|_|jS)NrÕÚ{rUcss|]}t|ƒVqdSr‰r²rÓryryrzrŒo szAnd.__str__..Ú}©r rÕr�rµrÐr°ryryrzr±j s    z And.__str__)T)T) r—r˜r™r¾rr r©rÌr/r>r±reryryrJrzr( s csDeZdZdZd‡fdd„ Zddd„Zdd „Zd d „Zd d „Z‡Z S)ra¾ Requires that at least one C{ParseExpression} is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the C{'^'} operator. Example:: # construct Or using '^' operator number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) print(number.searchString("123 3.1416 789")) prints:: [['123'], ['3.1416'], ['789']] Fcs:tt|ƒ ||¡|jr0tdd„|jDƒƒ|_nd|_dS)Ncss|] }|jVqdSr‰r×rÓryryrzrŒ… szOr.__init__..T)rIrr©rÐrQr–rÒrJryrzr©‚ sz Or.__init__Tc CsRd}d}g}|jD]š}z| ||¡}Wnvtk rb} zd| _| j|krR| }| j}W5d} ~ XYqtk rœt|ƒ|kr˜t|t|ƒ|j|ƒ}t|ƒ}YqX| ||f¡q|�r(|j dd„d�|D]^\} }z|  |||¡WStk �r$} z d| _| j|k�r| }| j}W5d} ~ XYqÈXqÈ|dk �r@|j|_ |‚nt||d|ƒ‚dS)NrtcSs |d SrÍry)Úxryryrzr{ž r|zOr.parseImpl..)rú no defined alternatives to match) rÐrÖr!rØr¢ræròrœrÚsortr´r£) r§rbr¢r®Ú maxExcLocÚ maxExceptionrrÄÚloc2rÓÚ_ryryrzr̉ s<      z Or.parseImplcCst|tƒrt |¡}| |¡Sr‰rÜr0ryryrzÚ__ixor__¯ s  z Or.__ixor__cCs@t|dƒr|jS|jdkr:dd dd„|jDƒ¡d|_|jS)NrÕrßz ^ css|]}t|ƒVqdSr‰r²rÓryryrzrŒ¹ szOr.__str__..ràrár°ryryrzr±´ s    z Or.__str__cCs,|dd…|g}|jD]}| |¡qdSr‰©rÐr>rÝryryrzr>½ s zOr.checkRecursion)F)T) r—r˜r™r¾r©rÌrér±r>reryryrJrzrt s   & csDeZdZdZd‡fdd„ Zddd„Zdd „Zd d „Zd d „Z‡Z S)ra½ Requires that at least one C{ParseExpression} is found. If two expressions match, the first one listed is the one that will match. May be constructed using the C{'|'} operator. Example:: # construct MatchFirst using '|' operator # watch the order of expressions to match number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] # put more selective expression first number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] Fcs:tt|ƒ ||¡|jr0tdd„|jDƒƒ|_nd|_dS)Ncss|] }|jVqdSr‰r×rÓryryrzrŒ× sz&MatchFirst.__init__..T)rIrr©rÐrQr–rÒrJryrzr©Ô szMatchFirst.__init__Tc CsÆd}d}|jD]Ž}z| |||¡}|WStk r`}z|j|krP|}|j}W5d}~XYqtk ršt|ƒ|kr–t|t|ƒ|j|ƒ}t|ƒ}YqXq|dk r´|j|_|‚nt||d|ƒ‚dS)Nrtrã)rÐr´r!r¢ræròrœr£) r§rbr¢r®rårærÄr‡rÓryryrzrÌÛ s$    zMatchFirst.parseImplcCst|tƒrt |¡}| |¡Sr‰rÜr0ryryrzÚ__ior__ó s  zMatchFirst.__ior__cCs@t|dƒr|jS|jdkr:dd dd„|jDƒ¡d|_|jS)NrÕrßú | css|]}t|ƒVqdSr‰r²rÓryryrzrŒý sz%MatchFirst.__str__..ràrár°ryryrzr±ø s    zMatchFirst.__str__cCs,|dd…|g}|jD]}| |¡qdSr‰rêrÝryryrzr>s zMatchFirst.checkRecursion)F)T) r—r˜r™r¾r©rÌrër±r>reryryrJrzrà s   cs<eZdZdZd ‡fdd„ Zd dd„Zdd„Zd d „Z‡ZS) ram Requires all given C{ParseExpression}s to be found, but in any order. Expressions may be separated by whitespace. May be constructed using the C{'&'} operator. Example:: color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") integer = Word(nums) shape_attr = "shape:" + shape_type("shape") posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") color_attr = "color:" + color("color") size_attr = "size:" + integer("size") # use Each (using operator '&') to accept attributes in any order # (shape and posn are required, color and size are optional) shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr) shape_spec.runTests(''' shape: SQUARE color: BLACK posn: 100, 120 shape: CIRCLE size: 50 color: BLUE posn: 50,80 color:GREEN size:20 shape:TRIANGLE posn:20,40 ''' ) prints:: shape: SQUARE color: BLACK posn: 100, 120 ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] - color: BLACK - posn: ['100', ',', '120'] - x: 100 - y: 120 - shape: SQUARE shape: CIRCLE size: 50 color: BLUE posn: 50,80 ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']] - color: BLUE - posn: ['50', ',', '80'] - x: 50 - y: 80 - shape: CIRCLE - size: 50 color: GREEN size: 20 shape: TRIANGLE posn: 20,40 ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']] - color: GREEN - posn: ['20', ',', '40'] - x: 20 - y: 40 - shape: TRIANGLE - size: 20 Tcs8tt|ƒ ||¡tdd„|jDƒƒ|_d|_d|_dS)Ncss|] }|jVqdSr‰r×rÓryryrzrŒ?sz Each.__init__..T)rIrr©rÑrÐr–r“ÚinitExprGroupsrÒrJryrzr©=sz Each.__init__c sî|jr’tdd„|jDƒƒ|_dd„|jDƒ}dd„|jDƒ}|||_dd„|jDƒ|_dd„|jDƒ|_dd„|jDƒ|_|j|j7_d |_|}|jdd…}|jdd…‰g}d } | �rj|ˆ|j|j} g} | D]v} z|  ||¡}Wn t k �r|   | ¡YqÜX|  |j  t | ƒ| ¡¡| |k�r@|  | ¡qÜ| ˆkr܈  | ¡qÜt| ƒt| ƒkrºd } qº|�r”d  d d„|Dƒ¡} t ||d | ƒ‚|‡fdd„|jDƒ7}g}|D]"} |  |||¡\}}|  |¡�q´t|tgƒƒ}||fS)Ncss&|]}t|tƒrt|jƒ|fVqdSr‰)r}rrNrcrÓryryrzrŒEs z!Each.parseImpl..cSsg|]}t|tƒr|j‘qSry©r}rrcrÓryryrzrêFs z"Each.parseImpl..cSs g|]}|jrt|tƒs|‘qSry)r–r}rrÓryryrzrêGs cSsg|]}t|tƒr|j‘qSry)r}r4rcrÓryryrzrêIs cSsg|]}t|tƒr|j‘qSry)r}rrcrÓryryrzrêJs cSs g|]}t|tttfƒs|‘qSry)r}rr4rrÓryryrzrêKsFTr3css|]}t|ƒVqdSr‰r²rÓryryrzrŒfsz*Missing one or more required elements (%s)cs$g|]}t|tƒr|jˆkr|‘qSryrîrÓ©ÚtmpOptryrzrêjs )ríràrÐÚopt1mapÚ optionalsÚmultioptionalsÚ multirequiredÚrequiredrÖr!rrìrNÚremoveròrµr´Úsumr$)r§rbr¢r®Úopt1Úopt2ÚtmpLocÚtmpReqdÚ matchOrderÚ keepMatchingÚtmpExprsÚfailedrÄÚmissingrÙr„Z finalResultsryrïrzrÌCsP    zEach.parseImplcCs@t|dƒr|jS|jdkr:dd dd„|jDƒ¡d|_|jS)NrÕrßz & css|]}t|ƒVqdSr‰r²rÓryryrzrŒyszEach.__str__..ràrár°ryryrzr±ts    z Each.__str__cCs,|dd…|g}|jD]}| |¡qdSr‰rêrÝryryrzr>}s zEach.checkRecursion)T)T) r—r˜r™r¾r©rÌr±r>reryryrJrzrs 5 1 csleZdZdZd‡fdd„ Zddd„Zdd „Z‡fd d „Z‡fd d „Zdd„Z gfdd„Z ‡fdd„Z ‡Z S)r za Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens. Fcsštt|ƒ |¡t|tƒr@ttjtƒr2t |¡}nt t |ƒ¡}||_ d|_ |dk r–|j |_ |j |_ | |j¡|j|_|j|_|j|_|j |j¡dSr‰)rIr r©r}râÚ issubclassr&rŒr.rrcr�r›r–r8r”r“r’r r˜r©r§rcr¢rJryrzr©‡s    zParseElementEnhance.__init__TcCs2|jdk r|jj|||dd�Std||j|ƒ‚dS)NFr rœ)rcr´r!rœrËryryrzrÌ™s zParseElementEnhance.parseImplcCs*d|_|j ¡|_|jdk r&|j ¡|Sré)r“rcrãr7r°ryryrzr7Ÿs    z#ParseElementEnhance.leaveWhitespacecsrt|tƒrB||jkrntt|ƒ |¡|jdk rn|j |jd¡n,tt|ƒ |¡|jdk rn|j |jd¡|Sr)r}r-r˜rIr r:rcr0rJryrzr:¦s    zParseElementEnhance.ignorecs&tt|ƒ ¡|jdk r"|j ¡|Sr‰)rIr rrcr°rJryrzr²s  zParseElementEnhance.streamlinecCsB||krt||gƒ‚|dd…|g}|jdk r>|j |¡dSr‰)r(rcr>)r§rÄrÞryryrzr>¸s  z"ParseElementEnhance.checkRecursioncCs6|dd…|g}|jdk r(|j |¡| g¡dSr‰©rcr@r>©r§r?rÕryryrzr@¿s  zParseElementEnhance.validatecsXztt|ƒ ¡WStk r$YnX|jdkrR|jdk rRd|jjt|jƒf|_|jSrÔ) rIr r±rƒr�rcr€r—rˆr°rJryrzr±ÅszParseElementEnhance.__str__)F)T) r—r˜r™r¾r©rÌr7r:rr>r@r±reryryrJrzr ƒs   cs*eZdZdZ‡fdd„Zddd„Z‡ZS)raõ Lookahead matching of the given parse expression. C{FollowedBy} does I{not} advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current position. C{FollowedBy} always returns a null token list. Example:: # use FollowedBy to match a label only if it is followed by a ':' data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint() prints:: [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] cstt|ƒ |¡d|_dSrÐ)rIrr©r–©r§rcrJryrzr©ászFollowedBy.__init__TcCs|j ||¡|gfSr‰)rcrÖrËryryrzrÌåszFollowedBy.parseImpl)TriryryrJrzrÐs cs2eZdZdZ‡fdd„Zd dd„Zdd„Z‡ZS) ra± Lookahead to disallow matching with the given parse expression. C{NotAny} does I{not} advance the parsing position within the input string, it only verifies that the specified parse expression does I{not} match at the current position. Also, C{NotAny} does I{not} skip over leading whitespace. C{NotAny} always returns a null token list. May be constructed using the '~' operator. Example:: cs0tt|ƒ |¡d|_d|_dt|jƒ|_dS)NFTzFound unwanted token, )rIrr©r“r–rˆrcrœrrJryrzr©õszNotAny.__init__TcCs&|j ||¡rt|||j|ƒ‚|gfSr‰)rcr×r!rœrËryryrzrÌüszNotAny.parseImplcCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)NrÕz~{rà©r rÕr�rˆrcr°ryryrzr±s   zNotAny.__str__)TržryryrJrzrês  cs(eZdZd‡fdd„ Zddd„Z‡ZS) Ú_MultipleMatchNcsFtt|ƒ |¡d|_|}t|tƒr.t |¡}|dk r<|nd|_dSrÐ) rIrr©r’r}râr&rŒÚ not_ender)r§rcÚstopOnÚenderrJryrzr© s   z_MultipleMatch.__init__Tc Cs¾|jj}|j}|jdk }|r$|jj}|r2|||ƒ||||dd�\}}zV|j } |r`|||ƒ| rp|||ƒ} n|} ||| |ƒ\}} | s�|  ¡rR|| 7}qRWnttfk r´YnX||fS©NFr ) rcr´rÆrrÖr˜rr!ræ) r§rbr¢r®Úself_expr_parseÚself_skip_ignorablesÚ check_enderÚ try_not_enderrÒÚhasIgnoreExprsrÑÚ tmptokensryryrzrÌs*      z_MultipleMatch.parseImpl)N)T)r—r˜r™r©rÌreryryrJrzr src@seZdZdZdd„ZdS)raƒ Repetition of one or more of the given expression. Parameters: - expr - expression that must match one or more times - stopOn - (default=C{None}) - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) text = "shape: SQUARE posn: upper left color: BLACK" OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] # use stopOn attribute for OneOrMore to avoid reading label string as part of the data attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] # could also be written as (attr_expr * (1,)).parseString(text).pprint() cCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)NrÕrßz}...rr°ryryrzr±Js   zOneOrMore.__str__N)r—r˜r™r¾r±ryryryrzr0scs8eZdZdZd ‡fdd„ Zd ‡fdd„ Zdd „Z‡ZS) r4aw Optional repetition of zero or more of the given expression. Parameters: - expr - expression that must match zero or more times - stopOn - (default=C{None}) - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) Example: similar to L{OneOrMore} Ncstt|ƒj||d�d|_dS)N)r T)rIr4r©r–)r§rcr rJryrzr©_szZeroOrMore.__init__Tc s<ztt|ƒ |||¡WSttfk r6|gfYSXdSr‰)rIr4rÌr!rærËrJryrzrÌcszZeroOrMore.parseImplcCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)NrÕr2ú]...rr°ryryrzr±is   zZeroOrMore.__str__)N)TržryryrJrzr4Ss c@s eZdZdd„ZeZdd„ZdS)Ú _NullTokencCsdSréryr°ryryrzrssz_NullToken.__bool__cCsdSr¡ryr°ryryrzr±vsz_NullToken.__str__N)r—r˜r™rr\r±ryryryrzrrsrcs6eZdZdZef‡fdd„ Zd dd„Zdd„Z‡ZS) raa Optional matching of the given expression. Parameters: - expr - expression that must match zero or more times - default (optional) - value to be returned if the optional expression is not found. Example:: # US postal code can be a 5-digit zip, plus optional 4-digit qualifier zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4))) zip.runTests(''' # traditional ZIP code 12345 # ZIP+4 form 12101-0001 # invalid ZIP 98765- ''') prints:: # traditional ZIP code 12345 ['12345'] # ZIP+4 form 12101-0001 ['12101-0001'] # invalid ZIP 98765- ^ FAIL: Expected end of text (at char 5), (line:1, col:6) cs.tt|ƒj|dd�|jj|_||_d|_dS)NFrgT)rIrr©rcr’rr–)r§rcrrJryrzr©�s zOptional.__init__Tc Cszz|jj|||dd�\}}WnTttfk rp|jtk rh|jjr^t|jgƒ}|j||jj<ql|jg}ng}YnX||fSr )rcr´r!rærÚ_optionalNotMatchedr‘r$)r§rbr¢r®rÒryryrzrÌ£s    zOptional.parseImplcCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)NrÕr2r5rr°ryryrzr±±s   zOptional.__str__)T) r—r˜r™r¾rr©rÌr±reryryrJrzrzs" cs,eZdZdZd ‡fdd„ Zd dd„Z‡ZS) r*aÿ Token for skipping over all undefined text until the matched expression is found. Parameters: - expr - target expression marking the end of the data to be skipped - include - (default=C{False}) if True, the target expression is also parsed (the skipped text and target expression are returned as a 2-element list). - ignore - (default=C{None}) used to define grammars (typically quoted strings and comments) that might contain false matches to the target expression - failOn - (default=C{None}) define expressions that are not allowed to be included in the skipped test; if found before the target expression is found, the SkipTo is not a match Example:: report = ''' Outstanding Issues Report - 1 Jan 2000 # | Severity | Description | Days Open -----+----------+-------------------------------------------+----------- 101 | Critical | Intermittent system crash | 6 94 | Cosmetic | Spelling error on Login ('log|n') | 14 79 | Minor | System slow when running too many reports | 47 ''' integer = Word(nums) SEP = Suppress('|') # use SkipTo to simply match everything up until the next SEP # - ignore quoted strings, so that a '|' character inside a quoted string does not match # - parse action will call token.strip() for each matched token, i.e., the description body string_data = SkipTo(SEP, ignore=quotedString) string_data.setParseAction(tokenMap(str.strip)) ticket_expr = (integer("issue_num") + SEP + string_data("sev") + SEP + string_data("desc") + SEP + integer("days_open")) for tkt in ticket_expr.searchString(report): print tkt.dump() prints:: ['101', 'Critical', 'Intermittent system crash', '6'] - days_open: 6 - desc: Intermittent system crash - issue_num: 101 - sev: Critical ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] - days_open: 14 - desc: Spelling error on Login ('log|n') - issue_num: 94 - sev: Cosmetic ['79', 'Minor', 'System slow when running too many reports', '47'] - days_open: 47 - desc: System slow when running too many reports - issue_num: 79 - sev: Minor FNcs`tt|ƒ |¡||_d|_d|_||_d|_t|t ƒrFt   |¡|_ n||_ dt |jƒ|_dS)NTFzNo match found for )rIr*r©Ú ignoreExprr–r›Ú includeMatchrÖr}râr&rŒÚfailOnrˆrcrœ)r§r$Úincluder:rrJryrzr©ñs zSkipTo.__init__Tc Cs&|}t|ƒ}|j}|jj}|jdk r,|jjnd}|jdk rB|jjnd} |} | |krÒ|dk rf||| ƒrfqâ| dk r˜z| || ƒ} Wqntk r”Yq˜YqnXqnz||| ddd�Wqâtt fk rÌ| d7} YqJXqâqJt|||j |ƒ‚| }|||…} t | ƒ} |j �r||||dd�\}} | | 7} || fS)NF)r®r¯r�r ) ròrcr´rr×rrÖrr!rærœr$r)r§rbr¢r®rerÉrcZ expr_parseÚself_failOn_canParseNextÚself_ignoreExpr_tryParseÚtmplocÚskiptextÚ skipresultrƒryryrzrÌþs:   zSkipTo.parseImpl)FNN)TriryryrJrzr*ºs6 csbeZdZdZd‡fdd„ Zdd„Zdd„Zd d „Zd d „Zgfd d„Z dd„Z ‡fdd„Z ‡Z S)raK Forward declaration of an expression to be defined later - used for recursive grammars, such as algebraic infix notation. When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator. Note: take care when assigning to C{Forward} not to overlook precedence of operators. Specifically, '|' has a lower precedence than '<<', so that:: fwdExpr << a | b | c will actually be evaluated as:: (fwdExpr << a) | b | c thereby leaving b and c out as parseable alternatives. It is recommended that you explicitly group the values inserted into the C{Forward}:: fwdExpr << (a | b | c) Converting to use the '<<=' operator instead will avoid this problem. See L{ParseResults.pprint} for an example of a recursive parser created using C{Forward}. Ncstt|ƒj|dd�dSrf)rIrr©r0rJryrzr©@szForward.__init__cCsjt|tƒrt |¡}||_d|_|jj|_|jj|_| |jj ¡|jj |_ |jj |_ |j   |jj ¡|Sr‰)r}râr&rŒrcr�r›r–r8r”r“r’r˜rr0ryryrzÚ __lshift__Cs      zForward.__lshift__cCs||>Sr‰ryr0ryryrzÚ __ilshift__PszForward.__ilshift__cCs d|_|Srér6r°ryryrzr7SszForward.leaveWhitespacecCs$|js d|_|jdk r |j ¡|SrÐ)ršrcrr°ryryrzrWs   zForward.streamlinecCs>||kr0|dd…|g}|jdk r0|j |¡| g¡dSr‰rrryryrzr@^s   zForward.validatecCsVt|dƒr|jS|jjdSz|jdk r4t|jƒ}nd}W5|j|_X|jjd|S)NrÕz: ...ÚNonez: )r rÕr€r—Z _revertClassÚ_ForwardNoRecursercrˆ)r§Ú retStringryryrzr±es     zForward.__str__cs.|jdk rtt|ƒ ¡Stƒ}||K}|SdSr‰)rcrIrrãr?rJryrzrãvs  z Forward.copy)N) r—r˜r™r¾r©rrr7rr@r±rãreryryrJrzr-s  c@seZdZdd„ZdS)r!cCsdS)Nr›ryr°ryryrzr±sz_ForwardNoRecurse.__str__N)r—r˜r™r±ryryryrzr!~sr!cs"eZdZdZd‡fdd„ Z‡ZS)r/zQ Abstract subclass of C{ParseExpression}, for converting parsed results. Fcstt|ƒ |¡d|_dSré)rIr/r©r’rrJryrzr©†szTokenConverter.__init__)FrhryryrJrzr/‚scs6eZdZdZd ‡fdd„ Z‡fdd„Zdd „Z‡ZS) r aÔ Converter to concatenate all matching tokens to a single string. By default, the matching patterns must also be contiguous in the input string; this can be disabled by specifying C{'adjacent=False'} in the constructor. Example:: real = Word(nums) + '.' + Word(nums) print(real.parseString('3.1416')) # -> ['3', '.', '1416'] # will also erroneously match the following print(real.parseString('3. 1416')) # -> ['3', '.', '1416'] real = Combine(Word(nums) + '.' + Word(nums)) print(real.parseString('3.1416')) # -> ['3.1416'] # no match when there are internal spaces print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...) rœTcs8tt|ƒ |¡|r| ¡||_d|_||_d|_dSrÐ)rIr r©r7Úadjacentr“Ú joinStringr )r§rcr$r#rJryrzr©›szCombine.__init__cs(|jrt ||¡ntt|ƒ |¡|Sr‰)r#r&r:rIr r0rJryrzr:¥szCombine.ignorecCsP| ¡}|dd…=|td | |j¡¡g|jd�7}|jrH| ¡rH|gS|SdS)Nrœ)r×)rãr$rµr6r$r�r‘r)r§rbr¢rÎÚretToksryryrzrϬs  "zCombine.postParse)rœT)r—r˜r™r¾r©r:rÏreryryrJrzr Šs cs(eZdZdZ‡fdd„Zdd„Z‡ZS)raù Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions. Example:: ident = Word(alphas) num = Word(nums) term = ident | num func = ident + Optional(delimitedList(term)) print(func.parseString("fn a,b,100")) # -> ['fn', 'a', 'b', '100'] func = ident + Group(Optional(delimitedList(term))) print(func.parseString("fn a,b,100")) # -> ['fn', ['a', 'b', '100']] cstt|ƒ |¡d|_dSrÐ)rIrr©r’rrJryrzr©ÄszGroup.__init__cCs|gSr‰ryrÍryryrzrÏÈszGroup.postParse©r—r˜r™r¾r©rÏreryryrJrzr¶s cs(eZdZdZ‡fdd„Zdd„Z‡ZS)r aW Converter to return a repetitive expression as a list, but also as a dictionary. Each element can also be referenced using the first token in the expression as its key. Useful for tabular report scraping when the first column can be used as a item key. Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) # print attributes as plain groups print(OneOrMore(attr_expr).parseString(text).dump()) # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names result = Dict(OneOrMore(Group(attr_expr))).parseString(text) print(result.dump()) # access named fields as dict entries, or output as dict print(result['shape']) print(result.asDict()) prints:: ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'} See more examples at L{ParseResults} of accessing fields by results name. cstt|ƒ |¡d|_dSrÐ)rIr r©r’rrJryrzr©ïsz Dict.__init__cCsît|ƒD]Ð\}}t|ƒdkrq|d}t|tƒr@t|dƒ ¡}t|ƒdkr\td|ƒ||<qt|ƒdkrŠt|dtƒsŠt|d|ƒ||<q| ¡}|d=t|ƒdks¶t|tƒrÆ|  ¡rÆt||ƒ||<qt|d|ƒ||<q|j ræ|gS|SdS)Nrr�rœrs) r÷ròr}rvrˆr¶rÅr$rãrr‘)r§rbr¢rÎrËÚtokÚikeyÚ dictvalueryryrzrÏós$   zDict.postParser&ryryrJrzr Ës# c@s eZdZdZdd„Zdd„ZdS)r-aV Converter for ignoring the results of a parsed expression. Example:: source = "a, b, c,d" wd = Word(alphas) wd_list1 = wd + ZeroOrMore(',' + wd) print(wd_list1.parseString(source)) # often, delimiters that are useful during parsing are just in the # way afterward - use Suppress to keep them out of the parsed output wd_list2 = wd + ZeroOrMore(Suppress(',') + wd) print(wd_list2.parseString(source)) prints:: ['a', ',', 'b', ',', 'c', ',', 'd'] ['a', 'b', 'c', 'd'] (See also L{delimitedList}.) cCsgSr‰ryrÍryryrzrÏszSuppress.postParsecCs|Sr‰ryr°ryryrzr5"szSuppress.suppressN)r—r˜r™r¾rÏr5ryryryrzr- sc@s(eZdZdZdd„Zdd„Zdd„ZdS) rzI Wrapper for parse actions, to ensure they are only called once. cCst|ƒ|_d|_dSré)r‡ÚcallableÚcalled)r§Z methodCallryryrzr©*s zOnlyOnce.__init__cCs.|js| |||¡}d|_|St||dƒ‚dS)NTrœ)r+r*r!)r§r�rlrxr„ryryrzr4-s zOnlyOnce.__call__cCs d|_dSré)r+r°ryryrzÚreset3szOnlyOnce.resetN)r—r˜r™r¾r©r4r,ryryryrzr&scs:tˆƒ‰‡fdd„}z ˆj|_Wntk r4YnX|S)at Decorator for debugging parse actions. When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".} When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised. Example:: wd = Word(alphas) @traceParseAction def remove_duplicate_chars(tokens): return ''.join(sorted(set(''.join(tokens)))) wds = OneOrMore(wd).setParseAction(remove_duplicate_chars) print(wds.parseString("slkdjs sld sldd sdlf sdljf")) prints:: >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) <>entering %s(line: '%s', %d, %r) z<.z)r‡r—r®)rFr3ryr2rzrd6s  ú,FcCs`t|ƒdt|ƒdt|ƒd}|rBt|t||ƒƒ |¡S|tt|ƒ|ƒ |¡SdS)aÇ Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing C{combine=True} in the constructor. If C{combine} is set to C{True}, the matching tokens are returned as a single token string, with the delimiters included; otherwise, the matching tokens are returned as a list of tokens, with the delimiters suppressed. Example:: delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc'] delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] z [rUrN)rˆr r4r¦r-)rcÚdelimÚcombineÚdlNameryryrzrBbs $csjtƒ‰‡‡fdd„}|dkr0ttƒ dd„¡}n| ¡}| d¡|j|dd�|ˆ d tˆƒd ¡S) a: Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value. Example:: countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] # in this parser, the leading integer value is given in binary, # '10' indicating that 2 values are in the array binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd'] cs.|d}ˆ|r ttˆg|ƒƒp&ttƒ>gSrÍ)rrrE)r�rlrxr$©Z arrayExprrcryrzÚcountFieldParseActionˆs"z+countedArray..countFieldParseActionNcSs t|dƒSrÍ)rvrwryryrzr{�r|zcountedArray..ÚarrayLenT©r¡z(len) r›)rr1rTr„rãr¦r¹rˆ)rcÚintExprr9ryr8rzr>us cCs6g}|D](}t|tƒr&| t|ƒ¡q| |¡q|Sr‰)r}rÝrrr)ÚLr‡rËryryrzr”s   rcs6tƒ‰‡fdd„}|j|dd�ˆ dt|ƒ¡ˆS)a* Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousLiteral(first) matchExpr = first + ":" + second will match C{"1:1"}, but not C{"1:2"}. Because this matches a previous literal, will also match the leading C{"1:1"} in C{"1:10"}. If this is not desired, use C{matchPreviousExpr}. Do I{not} use with packrat parsing enabled. csP|rBt|ƒdkrˆ|d>qLt| ¡ƒ}ˆtdd„|Dƒƒ>n ˆtƒ>dS)Nr�rcss|]}t|ƒVqdSr‰)r©rŠÚttryryrzrŒ²szDmatchPreviousLiteral..copyTokenToRepeater..)ròrrÖrr)r�rlrxÚtflat©ÚrepryrzÚcopyTokenToRepeater«s   z1matchPreviousLiteral..copyTokenToRepeaterTr;ú(prev) )rr¹r¦rˆ)rcrCryrArzrQ�s  csFtƒ‰| ¡}ˆ|K‰‡fdd„}|j|dd�ˆ dt|ƒ¡ˆS)aS Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousExpr(first) matchExpr = first + ":" + second will match C{"1:1"}, but not C{"1:2"}. Because this matches by expressions, will I{not} match the leading C{"1:1"} in C{"1:10"}; the expressions are evaluated first, and then compared, so C{"1"} is compared with C{"10"}. Do I{not} use with packrat parsing enabled. cs*t| ¡ƒ‰‡fdd„}ˆj|dd�dS)Ncs$t| ¡ƒ}|ˆkr tdddƒ‚dS)Nrœr)rrÖr!)r�rlrxÚ theseTokens©Ú matchTokensryrzÚmustMatchTheseTokensÌs zLmatchPreviousExpr..copyTokenToRepeater..mustMatchTheseTokensTr;)rrÖr„)r�rlrxrHrArFrzrCÊs  z.matchPreviousExpr..copyTokenToRepeaterTr;rD)rrãr¹r¦rˆ)rcÚe2rCryrArzrP¹s cCs:dD]}| |t|¡}q| dd¡}| dd¡}t|ƒS)Nz\^-]r@rTr·rº)r“Ú_bslashrˆ)r�r ryryrzr�Õs   r�Tc sÆ|rdd„}dd„}t‰ndd„}dd„}t‰g}t|tƒrF| ¡}n$t|tƒrZt|ƒ}ntjdt dd�|stt ƒSd }|t |ƒd k�r||}t ||d d …ƒD]R\}} || |ƒrÌ|||d =qxq¦||| ƒr¦|||d =|  || ¡| }qxq¦|d 7}qx|�s¤|�r¤zlt |ƒt d  |¡ƒk�rTtd d  dd„|Dƒ¡ƒ d |¡¡WStd dd„|Dƒ¡ƒ d |¡¡WSWn&tk �r¢tjdt dd�YnXt‡fdd„|Dƒƒ d |¡¡S)aÛ Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a C{L{MatchFirst}} for best performance. Parameters: - strs - a string of space-delimited literals, or a collection of string literals - caseless - (default=C{False}) - treat all literals as caseless - useRegex - (default=C{True}) - as an optimization, will generate a Regex object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or if creating a C{Regex} raises an exception) Example:: comp_oper = oneOf("< = > <= >= !=") var = Word(alphas) number = Word(nums) term = var | number comparison_expr = term + comp_oper + term print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12")) prints:: [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] cSs| ¡| ¡kSr‰)rt©r&Úbryryrzr{õr|zoneOf..cSs| ¡ | ¡¡Sr‰)rtrprKryryrzr{ör|cSs||kSr‰ryrKryryrzr{ùr|cSs | |¡Sr‰)rprKryryrzr{úr|z6Invalid argument to oneOf, expected string or iterablersrrr�Nrœz[%s]css|]}t|ƒVqdSr‰)r�©rŠÚsymryryrzrŒszoneOf..rìú|css|]}t |¡VqdSr‰)rŸr‘rMryryrzrŒsz7Exception creating Regex for oneOf, building MatchFirstc3s|]}ˆ|ƒVqdSr‰ryrM©ÚparseElementClassryrzrŒ$s)r rr}râr‘rrÝrrrrròr÷rrµr)r¦rƒr) ÚstrsrsÚuseRegexÚisequalÚmasksÚsymbolsrËÚcurrûr$ryrPrzrUÝsT    ÿ     **ÿ cCsttt||ƒƒƒS)aÜ Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} )r r4r)rrüryryrzrC&s!cCs^tƒ dd„¡}| ¡}d|_|dƒ||dƒ}|r@dd„}ndd„}| |¡|j|_|S) a� Helper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. By default, returns astring containing the original parsed text. If the optional C{asString} argument is passed as C{False}, then the return value is a C{L{ParseResults}} containing any results names that were originally matched, and a single token containing the original matched text from the input string. So if the expression passed to C{L{originalTextFor}} contains expressions with defined results names, you must set C{asString} to C{False} if you want to preserve those results name values. Example:: src = "this is test bold text normal text " for tag in ("b","i"): opener,closer = makeHTMLTags(tag) patt = originalTextFor(opener + SkipTo(closer) + closer) print(patt.searchString(src)[0]) prints:: [' bold text '] ['text'] cSs|Sr‰ry)r�r¢rxryryrzr{ar|z!originalTextFor..FÚ_original_startÚ _original_endcSs||j|j…Sr‰)rXrYrkryryrzr{fr|cSs&|| d¡| d¡…g|dd…<dS)NrXrY)rrkryryrzÚ extractTexthsz$originalTextFor..extractText)rr„rãr r˜)rcÚasStringÚ locMarkerÚ endlocMarkerÚ matchExprrZryryrzriIs  cCst|ƒ dd„¡S)zp Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. cSs|dSrÍryrwryryrzr{sr|zungroup..)r/r„)rcryryrzrjnscCs4tƒ dd„¡}t|dƒ|dƒ| ¡ ¡dƒƒS)a© Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - locn_start = location where matched expression begins - locn_end = location where matched expression ends - value = the actual parsed results Be careful if the input text contains C{} characters, you may want to call C{L{ParserElement.parseWithTabs}} Example:: wd = Word(alphas) for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [[0, 'ljsdf', 5]] [[8, 'lksdjjf', 15]] [[18, 'lkkjj', 23]] cSs|Sr‰ryrkryryrzr{‰r|zlocatedExpr..Ú locn_startrüÚlocn_end)rr„rrãr7)rcÚlocatorryryrzrlusz\[]-*.$+^?()~ ©r•cCs |ddSrñryrkryryrzr{”r|r{z\\0?[xX][0-9a-fA-F]+cCstt|d d¡dƒƒS)Nrz\0xé)ÚunichrrvÚlstriprkryryrzr{•r|z \\0[0-7]+cCstt|ddd…dƒƒS)Nrr�é)rdrvrkryryrzr{–r|z\]rÖr2rVÚnegateÚbodyr5csFdd„‰z"d ‡fdd„t |¡jDƒ¡WStk r@YdSXdS)aÜ Helper to easily define string ranges for use in Word construction. Borrows syntax from regexp '[]' string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" The input string must be enclosed in []'s, and the returned string is the expanded character set joined into a single string. The values enclosed in the []'s may be: - a single character - an escaped character with a leading backslash (such as C{\-} or C{\]}) - an escaped hex character with a leading C{'\x'} (C{\x21}, which is a C{'!'} character) (C{\0x##} is also supported for backwards compatibility) - an escaped octal character with a leading C{'\0'} (C{\041}, which is a C{'!'} character) - a range of any of the above, separated by a dash (C{'a-z'}, etc.) - any combination of the above (C{'aeiouy'}, C{'a-zA-Z0-9_$'}, etc.) cSs<t|tƒs|Sd dd„tt|dƒt|dƒdƒDƒ¡S)Nrœcss|]}t|ƒVqdSr‰)rdrŸryryrzrŒ­sz+srange....rr�)r}r$rµróÚord)Úpryryrzr{­r|zsrange..rœc3s|]}ˆ|ƒVqdSr‰ry)rŠÚpart©Ú _expandedryrzrŒ¯szsrange..N)rµÚ_reBracketExprrrhrƒrœryrlrzra›s "cs‡fdd„}|S)zt Helper method for defining parse actions that require matching at a specific column in the input text. cs"t||ƒˆkrt||dˆƒ‚dS)Nzmatched token not at column %drÉ)r^Úlocnrgr#ryrzÚ verifyCol¸sz!matchOnlyAtCol..verifyColry)r$rpryr#rzrO³s cs ‡fdd„S)a¹ Helper method for common parse actions that simply return a literal value. Especially useful when used with C{L{transformString}()}. Example:: num = Word(nums).setParseAction(lambda toks: int(toks[0])) na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) term = na | num OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] csˆgSr‰ryrk©ZreplStrryrzr{Ér|zreplaceWith..ryrqryrqrzr^½s cCs|ddd…S)a Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] rr�rtryrkryryrzr\Ës csN‡‡fdd„}ztˆdtˆdƒjƒ}Wntk rBtˆƒ}YnX||_|S)aG Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the parsed data to an integer using base 16. Example (compare the last to example in L{ParserElement.transformString}:: hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) hex_ints.runTests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).setParseAction(tokenMap(str.upper)) OneOrMore(upperword).runTests(''' my kingdom for a horse ''') wd = Word(alphas).setParseAction(tokenMap(str.title)) OneOrMore(wd).setParseAction(' '.join).runTests(''' now is the winter of our discontent made glorious summer by this sun of york ''') prints:: 00 11 22 aa FF 0a 0d 1a [0, 17, 34, 170, 255, 10, 13, 26] my kingdom for a horse ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] now is the winter of our discontent made glorious summer by this sun of york ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] cs‡‡fdd„|DƒS)Ncsg|]}ˆ|fˆžŽ‘qSryry)rŠÚtokn©r¦rmryrzrêúsz(tokenMap..pa..ryrkrsryrzr¿ùsztokenMap..par—r€)r‚r—rƒr)rmr¦r¿r†ryrsrzroÙs  ÿcCs t|ƒ ¡Sr‰©rˆrtrwryryrzr{r|cCs t|ƒ ¡Sr‰©rˆÚlowerrwryryrzr{r|c Cs¢t|tƒr|}t|| d�}n|j}tttdƒ}|r˜t ¡  t ¡}t dƒ|dƒt t t|t dƒ|ƒƒƒtddgd� d ¡  d d „¡t d ƒ}n†d  dd„tDƒ¡}t ¡  t ¡t|ƒB}t dƒ|dƒt t t|  t¡tt dƒ|ƒƒƒƒtddgd� d ¡  dd „¡t d ƒ}ttdƒ|d ƒ}| dd  | dd¡ ¡ ¡¡¡ d|¡}| dd  | dd¡ ¡ ¡¡¡ d|¡}||_||_||fS)zRInternal helper to construct opening and closing tag expressions, given a tag nameryz_-:rCÚtagú=ú/F©rrEcSs |ddkS©Nrryryrkryryrzr{r|z_makeTags..rDrœcss|]}|dkr|VqdS)rDNryrŸryryrzrŒsz_makeTags..cSs |ddkSr{ryrkryryrzr{r|rEr~ú:rUz<%s>r–z)r}rârrÕr1r6r5r@rãr„r\r-r r4rrr«rµrXr[rDr Ú_Lr“Útitler‘r¦rw)ÚtagStrÚxmlÚresnameÚ tagAttrNameÚ tagAttrValueÚopenTagZprintablesLessRAbrackÚcloseTagryryrzÚ _makeTags s> ÿþþÿÿýý..r†cCs t|dƒS)a  Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. Example:: text = 'More info at the pyparsing wiki page' # makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple a,a_end = makeHTMLTags("A") link_expr = a + SkipTo(a_end)("link_text") + a_end for link in link_expr.searchString(text): # attributes in the tag (like "href" shown here) are also accessible as named results print(link.link_text, '->', link.href) prints:: pyparsing -> http://pyparsing.wikispaces.com F©r†©rryryrzrM(scCs t|dƒS)zº Helper to construct opening and closing tag expressions for XML, given a tag name. Matches tags only in the given upper/lower case. Example: similar to L{makeHTMLTags} Tr‡rˆryryrzrN;scs8|r|dd…‰n| ¡‰dd„ˆDƒ‰‡fdd„}|S)a< Helper to create a validating parse action to be used with start tags created with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as C{} or C{
}. Call C{withAttribute} with a series of attribute names and values. Specify the list of filter attributes names and values as: - keyword arguments, as in C{(align="right")}, or - as an explicit dict with C{**} operator, when an attribute name is also a Python reserved word, as in C{**{"class":"Customer", "align":"right"}} - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) For attribute names with a namespace prefix, you must use the second form. Attribute names are matched insensitive to upper/lower case. If just testing for C{class} (with or without a namespace), use C{L{withClass}}. To verify that the attribute exists, but without specifying a value, pass C{withAttribute.ANY_VALUE} as the value. Example:: html = '''
Some text
1 4 0 1 0
1,3 2,3 1,1
this has no type
''' div,div_end = makeHTMLTags("div") # only match div tag having a type attribute with value "grid" div_grid = div().setParseAction(withAttribute(type="grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.searchString(html): print(grid_header.body) # construct a match with any div tag having a type attribute, regardless of the value div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.searchString(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 NcSsg|]\}}||f‘qSryryr=ryryrzrêzsz!withAttribute..csZˆD]P\}}||kr$t||d|ƒ‚|tjkr|||krt||d||||fƒ‚qdS)Nzno matching attribute z+attribute '%s' has value '%s', must be '%s')r!rgÚ ANY_VALUE)r�rlrÒÚattrNameÚ attrValue©Úattrsryrzr¿{s  ÿzwithAttribute..pa)rö)r¦ZattrDictr¿ryrŒrzrgDs 2 cCs|r d|nd}tf||iŽS)aã Simplified version of C{L{withAttribute}} when matching on a div class - made difficult because C{class} is a reserved word in Python. Example:: html = '''
Some text
1 4 0 1 0
1,3 2,3 1,1
this <div> has no class
''' div,div_end = makeHTMLTags("div") div_grid = div().setParseAction(withClass("grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.searchString(html): print(grid_header.body) div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.searchString(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 z%s:classÚclass)rg)Ú classnameÚ namespaceÚ classattrryryrzrm…s ú(r¨cCsštƒ}||||B}t|ƒD�]l\}}|ddd…\}} } } | dkrPd|nd|} | dkr„|dkstt|ƒdkr|tdƒ‚|\} }tƒ | ¡}| tjk�r^| d krÂt||ƒt|t |ƒƒ}nš| dk�r|dk rút|||ƒt|t ||ƒƒ}nt||ƒt|t |ƒƒ}nD| dk�rTt|| |||ƒt|| |||ƒ}ntd ƒ‚nì| tj k�rB| d k�r¤t |t ƒ�sˆt |ƒ}t|j |ƒt||ƒ}nœ| dk�rü|dk �rÞt|||ƒt|t ||ƒƒ}nt||ƒt|t |ƒƒ}nD| dk�r8t|| |||ƒt|| |||ƒ}ntd ƒ‚ntd ƒ‚| �rvt | ttfƒ�rl|j| Žn | | ¡|| | ¡|BK}|}q||K}|S) aD Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. The generated parser will also recognize the use of parentheses to override operator precedences (see example below). Note: if you define a deep operator list, you may see performance issues when using infixNotation. See L{ParserElement.enablePackrat} for a mechanism to potentially improve your parser performance. Parameters: - baseExpr - expression representing the most basic element for the nested - opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form (opExpr, numTerms, rightLeftAssoc, parseAction), where: - opExpr is the pyparsing expression for the operator; may also be a string, which will be converted to a Literal; if numTerms is 3, opExpr is a tuple of two expressions, for the two operators separating the 3 terms - numTerms is the number of terms for this operator (must be 1, 2, or 3) - rightLeftAssoc is the indicator whether the operator is right or left associative, using the pyparsing-defined constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}. - parseAction is the parse action to be associated with expressions matching this operator expression (the parse action tuple member may be omitted); if the parse action is passed a tuple or list of functions, this is equivalent to calling C{setParseAction(*fn)} (L{ParserElement.setParseAction}) - lpar - expression for matching left-parentheses (default=C{Suppress('(')}) - rpar - expression for matching right-parentheses (default=C{Suppress(')')}) Example:: # simple example of four-function arithmetic with ints and variable names integer = pyparsing_common.signed_integer varname = pyparsing_common.identifier arith_expr = infixNotation(integer | varname, [ ('-', 1, opAssoc.RIGHT), (oneOf('* /'), 2, opAssoc.LEFT), (oneOf('+ -'), 2, opAssoc.LEFT), ]) arith_expr.runTests(''' 5+3*6 (5+3)*6 -2--11 ''', fullDump=False) prints:: 5+3*6 [[5, '+', [3, '*', 6]]] (5+3)*6 [[[5, '+', 3], '*', 6]] -2--11 [[['-', 2], '-', ['-', 11]]] r‰Nršrqz%s termz %s%s termrsz@if numterms=3, opExpr must be a tuple or list of two expressionsr�z6operator must be unary (1), binary (2), or ternary (3)z2operator must indicate right or left associativity)rr÷ròr(r¦rVÚLEFTrrrÚRIGHTr}rrcr'rÝr„)ZbaseExprZopListÚlparÚrparr‡ÚlastExprrËÚoperDefÚopExprÚarityÚrightLeftAssocr¿ZtermNameÚopExpr1ÚopExpr2ÚthisExprr^ryryrzrk¬sZ=   & ÿ      & ÿ   z4"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*ú"z string enclosed in double quotesz4'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*ú'z string enclosed in single quotesz*quotedString using single or double quotesÚuzunicode string literalcCsž||krtdƒ‚|dk�r*t|tƒ�r"t|tƒ�r"t|ƒdkr¨t|ƒdkr¨|dk r‚tt|t||tjdd�ƒƒ  dd„¡}n$t   ¡t||tjƒ  dd„¡}nx|dk rìtt|t |ƒt |ƒttjdd�ƒƒ  dd„¡}n4ttt |ƒt |ƒttjdd�ƒƒ  d d„¡}ntd ƒ‚t ƒ}|dk �rd|tt|ƒt||B|Bƒt|ƒƒK}n$|tt|ƒt||Bƒt|ƒƒK}| d ||f¡|S) a~ Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression - content - expression for items within the nested lists (default=C{None}) - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString}) If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the C{ignoreExpr} argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. The default is L{quotedString}, but if no expressions are to be ignored, then pass C{None} for this argument. Example:: data_type = oneOf("void int short long char float double") decl_data_type = Combine(data_type + Optional(Word('*'))) ident = Word(alphas+'_', alphanums+'_') number = pyparsing_common.number arg = Group(decl_data_type + ident) LPAR,RPAR = map(Suppress, "()") code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) c_function = (decl_data_type("type") + ident("name") + LPAR + Optional(delimitedList(arg), [])("args") + RPAR + code_body("body")) c_function.ignore(cStyleComment) source_code = ''' int is_odd(int x) { return (x%2); } int dec_to_hex(char hchar) { if (hchar >= '0' && hchar <= '9') { return (ord(hchar)-ord('0')); } else { return (10+ord(hchar)-ord('A')); } } ''' for func in c_function.searchString(source_code): print("%(name)s (%(type)s) args: %(args)s" % func) prints:: is_odd (int) args: [['int', 'x']] dec_to_hex (int) args: [['char', 'hchar']] z.opening and closing strings cannot be the sameNr�rbcSs |d ¡SrÍ©r¶rwryryrzr{gr|znestedExpr..cSs |d ¡SrÍr¢rwryryrzr{jr|cSs |d ¡SrÍr¢rwryryrzr{pr|cSs |d ¡SrÍr¢rwryryrzr{tr|zOopening and closing arguments must be strings if no content expression is givenznested %s%s expression)r(r}râròr rr r&rˆr„rErãrrrr-r4r¦)ÚopenerÚcloserÚcontentrr‡ryryrzrR%sH: ÿþÿÿÿ þý ÿþ *$c sä‡fdd„}‡fdd„}‡fdd„}ttƒ d¡ ¡ƒ}tƒtƒ |¡ d¡}tƒ |¡ d ¡}tƒ |¡ d ¡} |r¦tt|ƒ|t|t|ƒt|ƒƒ| ƒ} n$tt|ƒt|t|ƒt|ƒƒƒ} |  t tƒ¡|  d ¡S) a Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements (default=C{True}) A valid block must contain at least one C{blockStatement}. Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group( funcDecl + func_body ) rvalue = Forward() funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << ( funcDef | assignment | identifier ) module_body = OneOrMore(stmt) parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] csN|t|ƒkrdSt||ƒ}|ˆdkrJ|ˆdkr>t||dƒ‚t||dƒ‚dS)Nrtzillegal nestingznot a peer entry)ròr;r#r!©r�rlrxÚcurCol©Ú indentStackryrzÚcheckPeerIndentÍs     z&indentedBlock..checkPeerIndentcs2t||ƒ}|ˆdkr"ˆ |¡n t||dƒ‚dS)Nrtznot a subentry)r;rr!r¦r¨ryrzÚcheckSubIndentÕs   z%indentedBlock..checkSubIndentcsN|t|ƒkrdSt||ƒ}ˆr6|ˆdkr6|ˆdksBt||dƒ‚ˆ ¡dS)Nrtrpznot an unindent)ròr;r!rr¦r¨ryrzÚ checkUnindentÜs    z$indentedBlock..checkUnindentz ÚINDENTrœÚUNINDENTzindented block) rrr8r5rr„r¦rrr:rJ) ÚblockStatementExprr©rGrªr«r¬rTr­ÚPEERÚUNDENTÚsmExprryr¨rzrhs(N   þþþÿz#[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]z[\0xa1-\0xbf\0xd7\0xf7]z_:zany tagzgt lt amp nbsp quot aposz><& "'z &(?PrOz);zcommon HTML entitycCs t |j¡S)zRHelper parser action to replace common HTML entities with their special characters)Ú_htmlEntityMaprìÚentityrwryryrzr]÷sz/\*(?:[^*]|\*(?!/))*z*/zC style commentzz HTML commentz.*z rest of linez//(?:\\\n|[^\n])*z // commentzC++ style commentz#.*zPython style commentr…ú Ú commaItemrzc@s¨eZdZdZeeƒZeeƒZe e ƒ  d¡  e¡Z e eƒ  d¡  eedƒ¡Zedƒ  d¡  e¡Zeƒ  e¡deƒ  e¡  d¡Ze d d „¡eeeed ƒ ¡eƒB  d ¡Ze e¡ed ƒ  d¡  e¡Zedƒ  d¡  e¡ZeeBeB ¡Zedƒ  d¡  e¡Ze ededƒ  d¡Zedƒ  d¡Z edƒ  d¡Z!e!de!d  d¡Z"ee!de!dƒdee!de!dƒ  d¡Z#e# $dd „¡d e   d!¡Z%e&e"e%Be#B  d"¡ƒ  d"¡Z'ed#ƒ  d$¡Z(e)d=d&d'„ƒZ*e)d>d)d*„ƒZ+ed+ƒ  d,¡Z,ed-ƒ  d.¡Z-ed/ƒ  d0¡Z.e/ ¡e0 ¡BZ1e)d1d2„ƒZ2e&e3e4d3ƒe5ƒe e6d3d4�ee7d5ƒƒƒƒ ¡  d6¡Z8e9ee: ;¡e8Bd7d8�ƒ  d9¡Zd}, L{reals}, L{scientific notation}) - common L{programming identifiers} - network addresses (L{MAC}, L{IPv4}, L{IPv6}) - ISO8601 L{dates} and L{datetime} - L{UUID} - L{comma-separated list} Parse actions: - C{L{convertToInteger}} - C{L{convertToFloat}} - C{L{convertToDate}} - C{L{convertToDatetime}} - C{L{stripHTMLTags}} - C{L{upcaseTokens}} - C{L{downcaseTokens}} Example:: pyparsing_common.number.runTests(''' # any int or real number, returned as the appropriate type 100 -100 +100 3.14159 6.02e23 1e-12 ''') pyparsing_common.fnumber.runTests(''' # any int or real number, returned as float 100 -100 +100 3.14159 6.02e23 1e-12 ''') pyparsing_common.hex_integer.runTests(''' # hex numbers 100 FF ''') pyparsing_common.fraction.runTests(''' # fractions 1/2 -3/4 ''') pyparsing_common.mixed_integer.runTests(''' # mixed fractions 1 1/2 -3/4 1-3/4 ''') import uuid pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) pyparsing_common.uuid.runTests(''' # uuid 12345678-1234-5678-1234-567812345678 ''') prints:: # any int or real number, returned as the appropriate type 100 [100] -100 [-100] +100 [100] 3.14159 [3.14159] 6.02e23 [6.02e+23] 1e-12 [1e-12] # any int or real number, returned as float 100 [100.0] -100 [-100.0] +100 [100.0] 3.14159 [3.14159] 6.02e23 [6.02e+23] 1e-12 [1e-12] # hex numbers 100 [256] FF [255] # fractions 1/2 [0.5] -3/4 [-0.75] # mixed fractions 1 [1] 1/2 [0.5] -3/4 [-0.75] 1-3/4 [1.75] # uuid 12345678-1234-5678-1234-567812345678 [UUID('12345678-1234-5678-1234-567812345678')] Úintegerz hex integerrcz[+-]?\d+zsigned integerryÚfractioncCs|d|dS)Nrrtryrwryryrzr{´r|zpyparsing_common.rÖz"fraction or mixed integer-fractionz [+-]?\d+\.\d*z real numberz+[+-]?\d+([eE][+-]?\d+|\.\d*([eE][+-]?\d+)?)z$real number with scientific notationz[+-]?\d+\.?\d*([eE][+-]?\d+)?ÚfnumberrèÚ identifierzK(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}z IPv4 addressz[0-9a-fA-F]{1,4}Ú hex_integerr|ézfull IPv6 address)rrzz::zshort IPv6 addresscCstdd„|DƒƒdkS)Ncss|]}tj |¡rdVqdSrA)rpÚ _ipv6_partrr>ryryrzrŒÐs z,pyparsing_common...rf)r÷rwryryrzr{Ðr|z::ffff:zmixed IPv6 addressz IPv6 addressz:[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}z MAC addressú%Y-%m-%dcs‡fdd„}|S)aØ Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"}) Example:: date_expr = pyparsing_common.iso8601_date.copy() date_expr.setParseAction(pyparsing_common.convertToDate()) print(date_expr.parseString("1999-12-31")) prints:: [datetime.date(1999, 12, 31)] c sNzt |dˆ¡ ¡WStk rH}zt||t|ƒƒ‚W5d}~XYnXdSrÍ)rÚstrptimeÚdater(r!r©r�rlrxÚve©ÚfmtryrzÚcvt_fnçsz.pyparsing_common.convertToDate..cvt_fnry©rÄrÅryrÃrzÚ convertToDateØs zpyparsing_common.convertToDateú%Y-%m-%dT%H:%M:%S.%fcs‡fdd„}|S)a Helper to create a parse action for converting parsed datetime string to Python datetime.datetime Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"}) Example:: dt_expr = pyparsing_common.iso8601_datetime.copy() dt_expr.setParseAction(pyparsing_common.convertToDatetime()) print(dt_expr.parseString("1999-12-31T23:59:59.999")) prints:: [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] c sJzt |dˆ¡WStk rD}zt||t|ƒƒ‚W5d}~XYnXdSrÍ)rr¿r(r!rrÁrÃryrzrÅýsz2pyparsing_common.convertToDatetime..cvt_fnryrÆryrÃrzÚconvertToDatetimeîs z"pyparsing_common.convertToDatetimez7(?P\d{4})(?:-(?P\d\d)(?:-(?P\d\d))?)?z ISO8601 datez†(?P\d{4})-(?P\d\d)-(?P\d\d)[T ](?P\d\d):(?P\d\d)(:(?P\d\d(\.\d*)?)?)?(?PZ|[+-]\d\d:?\d\d)?zISO8601 datetimez2[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}ÚUUIDcCstj |d¡S)a Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = 'More info at the
pyparsing wiki page' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' r)rpÚ_html_stripperr…)r�rlrÒryryrzÚ stripHTMLTagss zpyparsing_common.stripHTMLTagsr4r…rµr¶rœrzzcomma separated listcCs t|ƒ ¡Sr‰rtrwryryrzr{"r|cCs t|ƒ ¡Sr‰rurwryryrzr{%r|N)r¾)rÈ)?r—r˜r™r¾rorvÚconvertToIntegerÚfloatÚconvertToFloatr1rTr¦r„r·rFr»r)Úsigned_integerr¸r¹rr5Ú mixed_integerr÷ÚrealÚsci_realrÚnumberr¹r6r5rºÚ ipv4_addressr½Ú_full_ipv6_addressÚ_short_ipv6_addressrÀÚ_mixed_ipv6_addressr Ú ipv6_addressÚ mac_addressrcrÇrÉÚ iso8601_dateÚiso8601_datetimeÚuuidr9r8rËrÌrrrrXr0Ú _commasepitemrBr[rãÚcomma_separated_listrfrDryryryrzrpsV"" 2     ÿ ÿÚ__main__ÚselectÚfromrqr-)r6Úcolumnsr§ZtablesÚcommandaK # '*' as column list and dotted table name select * from SYS.XYZZY # caseless match on "SELECT", and casts back to "select" SELECT * from XYZZY, ABC # list of column names, and mixed case SELECT keyword Select AA,BB,CC from Sys.dual # multiple tables Select A, B, C from Sys.dual, Table2 # invalid SELECT keyword - should fail Xelect A, B, C from Sys.dual # incomplete command - should fail Select # invalid column name - should fail Select ^^^ frox Sys.dual z] 100 -100 +100 3.14159 6.02e23 1e-12 z 100 FF z6 12345678-1234-5678-1234-567812345678 )rs)r4F)N)FT)T)rœ)T)ãr¾Ú __version__Ú__versionTime__Ú __author__r�Úweakrefrrírãr‚rrŸr¢rõrUrtrãrÚ_threadrÚ ImportErrorÚ threadingÚcollections.abcrrrrïZ ordereddictÚ__all__r'Ú version_inforsr>ÚmaxsizerdrrâÚchrrdrˆr÷ròrOÚreversedrÝrßrQrÑr“r”r�ZmaxintÚxrangeróÚ __builtin__r‘Úfnamerr‚r®r¼rßr•rÑr–Úascii_uppercaseÚascii_lowercaser6rTrFr5rJrµÚ printablerXrƒrr!r#r%r(rÅr$Úregisterr;rLrIrdrhrjrSr‡r&r.rrrr}rŒrr r rnr1r)r'r r0rÅrrrr,r+r3r2r"rrrrr rrrrr4rrrr*rr!r/r rr r-rrdrBr>rrQrPr�rUrCrirjrlr¦rErKrJrcrbr„Ú _escapedPuncÚ_escapedHexCharÚ_escapedOctCharÚ _singleCharÚ _charRanger«rnrarOr^r\rorfrDr†rMrNrgr‰rmrVr“r”rkrWr@r`r[rerRrhr7rYr9r8ràr’r³rr=r]r:rGr7r_rAr?rHrZrrÞr<rpr—Z selectTokenZ fromTokenÚidentZ columnNameZcolumnNameListZ columnSpecZ tableNameZ tableNameListZ simpleSQLrbrÔr¹r»rÝrÊryryryrzÚs¦ÿ4    î    8      @v &A= I G3pLOD|M &#@sQ,A,    I# %     0 ,   ? #p  ÿÿZr   (   ÿÿÿ þ     "