U ʗRe`A @sUddlZddlZddlmZmZmZmZmZmZmZm Z m Z m Z ddl m Z mZddlmZddlZddlZddlZddlZddlZddlmZddlZddlZddlmZddlmZddlmZdd l m!Z!d d l"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z+m,Z-d d l.Td d l/Td d l0m1Z1m2Z2d dl3m4Z4ej5Z6e7e8fZ9ee:dfe;d<ejGddde%Z?GdddeZ@e@ddddZAe@ddddZBdd d!d"ZC[%eje7ejDe7eEd#d$d%ZFeFejGejHId&r eCeJeKeLeMeNeOePeQeReSeTh ZUejVZWeegefee1gefeeXe1gefee7eXe1geffZYeegeEfee1geEfeeXe1geEfee7eXe1geEffZZee7eXd'e[gdfZ\ee7eXd'eEgdfZ]ee7eXeXd'e1eEgdfZ^ee7eXd'e[eEgdfZ_ej`ejaZbe4jcjdZde4jcjeZed(Zfefd)ZgebefZhd*id+d,ejjDZkdalejme;d-<dd/d0ZndeZe7eEeYd2d3d4Zode7eXd'eEd5d6d7Zpde7eXeXd'e1eEd8d9d:Zqde7eXd'e[eEd;dd?ZsGd@d'd'e ZtGdAdBdBetZuGdCdDdDetZvGdEdFdFevZwGdGdHdHevZxGdIdJdJevZyGdKdLdLeyZzeyet_{GdMdNdNevZ|GdOdPdPeyZ}GdQdRdRe|Z~GdSdTdTevZGdUdVdVevZGdWdXdXeZGdYdZdZeZGd[d\d\evZGd]d^d^evZGd_d`d`evZGdadbdbevZGdcddddevZGdedfdfeZGdgdhdheZGdidjdjeZGdkdldleZGdmdndneZGdodpdpeZGdqdrdreZGdsdtdtetZGdudvdveZGdwdxdxeZGdydzdzeZGd{d|d|eZGd}d~d~etZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddZGdddeZeZDGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZeYeYdddZewdZedZedZedZedZee(dddddZedddZedddZeeBeBedd dBZeeedeZeydeddeeeeBddZe7e7dddZeYd ddZdd ddÄZeedăddơZeedǃddɡZeedădedǃdBdʡZeded̡Zed̓Zed΃Zdd,eDZeete;d<eZeoZesZeZeZeZeZeZeZeZeZeZdS)N) NamedTupleUnionCallableAny GeneratorTupleListTextIOSetSequence)ABCabstractmethod)Enum)Iterable) itemgetter)wraps)RLock)Path) _FifoCache_UnboundedCache__config_flags_collapse_string_to_ranges_escape_regex_range_chars_bslash_flattenLRUMemo UnboundedMemo)*) ParseResults_ParseResultsWithOffset)pyparsing_unicode.str_type))cached_propertyc@seZdZddZdddZdS)r%cCs ||_dSN)_func)selffuncr*/builddir/build/BUILDROOT/alt-python38-pip-22.2.1-2.el8.x86_64/opt/alt/python38/lib/python3.8/site-packages/pip/_vendor/pyparsing/core.py__init__Qszcached_property.__init__NcCs||}|j|jj<|Sr&)r'__dict____name__)r(instanceownerretr*r*r+__get__Tszcached_property.__get__)N)r. __module__ __qualname__r,r2r*r*r*r+r%Psr%c@s0eZdZdZdZdZddeDZdZ dS) __compat__aJ A cross-version compatibility configuration for pyparsing features that will be released in a future version. By setting values in this configuration to True, those features can be enabled in prior versions for compatibility development and testing. - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`; maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1 behavior compatibilityTcCsg|]}|ds|qS_ startswith.0__r*r*r+ js z__compat__.z( collect_all_And_tokens N) r.r3r4__doc__ _type_desccollect_all_And_tokenslocals _all_namessplit _fixed_namesr*r*r*r+r5Ys  r5c@sneZdZdZdZdZdZdZdZdZ dZ dZ dde DZ dde DZdde DZeddd d ZdS) __diag__ diagnosticFcCsg|]}|ds|qSr7r9r;r*r*r+r>|s z__diag__.cCsg|]}|dr|qS)warnr9r<namer*r*r+r>}s cCsg|]}|dr|qS)Z enable_debugr9rIr*r*r+r>~s NreturncCs|jD]}||qdSr&)_warning_namesenable)clsrJr*r*r+enable_all_warningss z__diag__.enable_all_warnings)r.r3r4r@)warn_multiple_tokens_in_named_alternation)warn_ungrouped_named_tokens_in_collectionwarn_name_set_on_empty_Forward!warn_on_parse_using_empty_Forwardwarn_on_assignment_to_Forward%warn_on_multiple_string_args_to_oneof(warn_on_match_first_with_lshift_operator!enable_debug_on_named_expressionsrBrCrM _debug_names classmethodrPr*r*r*r+rFpsrFc@s0eZdZdZdZdZdZdZdZdZ dZ d Z d S) Diagnosticsa Diagnostic configuration (all default to disabled) - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results name is defined on a containing expression with ungrouped subexpressions that also have results names - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined with a results name, but has no contents defined - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined in a grammar but has never had an expression attached to it - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'`` - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is incorrectly called with multiple str arguments - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent calls to :class:`ParserElement.set_name` Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`. All warnings can be enabled by calling :class:`enable_all_warnings`. rrr#N) r.r3r4r?rQrRrSrTrUrVrWrXr*r*r*r+r[sr[) diag_enumrLcCst|jdS)zO Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`). N)rFrNrJrar*r*r+ enable_diagsrccCst|jdS)zP Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). N)rFdisablerJrbr*r*r+ disable_diagsrerKcCs tdS)zU Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`). N)rFrPr*r*r*r+rPsrP)cmd_line_warn_options warn_env_varrLc Csxt|}|D]f}|dddd\}}}}}|dsX|sJ|sJ|rR|dkrXd}q |dr |dkr d}q |S) Nz:::::r^i pyparsingT)rjF)boolrDlowerr:) rfrgrNwarn_optw_action w_message w_categoryw_modulew_liner*r*r+_should_enable_warningss(rtZPYPARSINGENABLEALLWARNINGS ParserElement 0123456789Z ABCDEFabcdefrkcCsg|]}|tjkr|qSr*)string whitespacer<cr*r*r+r>s r>_trim_arity_call_liner#cstkrfddSdddddd}tp z_trim_arity..rFcSs$tj||d}|d}|ddgS)Nlimitr\) traceback extract_tb)tbrframes frame_summaryr*r*r+rsz_trim_arity..extract_tbr`r\rrrc sz|d}d|WStk r}zNr4nB|j}|dddddk}~|rtkrtd7WYqW5d}~XYqXqdS)NTr\rrr) TypeError __traceback__)argsr1tertrim_arity_type_errorr found_arityr)r max_limitpa_call_line_synthr*r+wrappers z_trim_arity..wrapperr. __class__)r)_single_arg_builtinsr{r extract_stackgetattrr.r?)r)r LINE_DIFFr func_namer*rr+ _trim_aritys  rF)fnmessagefatalrLcs@|dk r |nd|rtntttfdd}|S)aC Function to convert a simple predicate function that returns ``True`` or ``False`` into a parse action. Can be used in places when a parse action is required and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition to an operator level in :class:`infix_notation`). Optional keyword arguments: - ``message`` - define a custom message to be used in the raised exception - ``fatal`` - if True, will raise :class:`ParseFatalException` to stop parsing immediately; otherwise will raise :class:`ParseException` Nzfailed user-defined conditioncs t|||s||dSr&)rlr|exc_typermsgr*r+paVsz%condition_as_parse_action..pa)ParseFatalExceptionParseExceptionrr)rrrrr*rr+condition_as_parse_actionBs  r)instringlocexpr cache_hitc CsJ|rdnd}td|||t||t||t||dt||ddS)Nrrkz&{}Match {} at loc {}({},{}) {} {}^ r)printformatlinenocolline)rrrr cache_hit_strr*r*r+_default_start_debug_action^s r)rstartlocendlocrtoksrcCs&|rdnd}td|||dS)Nrrkz{}Matched {} -> {})rras_list)rrrrrrrr*r*r+_default_success_debug_actionqs r)rrrexcrcCs*|rdnd}td||t|j|dS)Nrrkz {}Match {} failed, {} raised: {})rrtyper.)rrrrrrr*r*r+_default_exception_debug_action}s rcGsdS)zG'Do-nothing' debug action, to suppress debugging output during parsing.Nr*)rr*r*r+null_debug_actionsrc@steZdZUdZdZeed<dZeed<dZ e j e ed<e eddd d Ze e dd d d ZGdddeZdedddZeddddZddddZdddeeeddddZdddZdedd d!d"Zedd#d$d%Zedd#d&d'Zedd#d(d)Zedd*d+d,Zd-d.Z d/d0Z!dd1d2Z"d3d4Z#de$e%e&fdd5d6Z'dee%ee%d7d8d9Z(ee%ed:d;d<Z)e*Z+iZ,e j-e$e%d=efe$e%e.e&e/fffed><iZ0e*Z1d?d?gZ2de$e%e&fdd@dAZ3e'Z4e dddBdCZ5dZ6dZ7e dddDdEZ8e dddFe j e%ddGdHdIZ9e dddFe%eddKdLdMZ:dddNeeee&dOdPdQZ;eddVeeedWdXdYZ?eZe@Ze?ZeVZeWZe\Ze]Ze_ZebZemZesZeSZeTZdS)ruz)Abstract base level parser element class.z DEFAULT_WHITE_CHARSFverbose_stacktraceN_literalStringClass)charsrLcCs$|t_tD]}|jr t||_q dS)a Overrides the default whitespace chars Example:: # default whitespace chars are space, and newline Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.set_default_whitespace_chars(" \t") Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def'] N)rur_builtin_exprscopyDefaultWhiteCharsset whiteChars)rrr*r*r+set_default_whitespace_charssz*ParserElement.set_default_whitespace_chars)rOrLcCs |t_dS)al 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.parse_string("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inline_literals_using(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parse_string("1999/12/31") # -> ['1999', '12', '31'] N)rur)rOr*r*r+inline_literals_usingsz#ParserElement.inline_literals_usingc@s8eZdZUejeed<ejeed<ejeed<dS)zParserElement.DebugActions debug_try debug_match debug_failN) r.r3r4typingOptionalDebugStartAction__annotations__DebugSuccessActionDebugExceptionActionr*r*r*r+ DebugActionss rsavelistcCst|_d|_d|_d|_d|_||_d|_tt j |_ d|_ d|_ d|_t|_d|_d|_d|_d|_d|_|ddd|_d|_d|_g|_dS)NTFrk)list parseAction failAction customName _defaultName resultsName saveAsListskipWhitespacerrurrrmayReturnEmptykeepTabs ignoreExprsdebug streamlined mayIndexErrorerrmsg modalResultsr debugActions callPreparse callDuringTrysuppress_warnings_)r(rr*r*r+r,s* zParserElement.__init__) warning_typerLcCs|j||S)aY Suppress warnings emitted for a particular diagnostic on this expression. Example:: base = pp.Forward() base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward) # statement would normally raise a warning, but is now suppressed print(base.parseString("x")) )rappend)r(rr*r*r+suppress_warnings zParserElement.suppress_warningrKcCs@t|}|jdd|_|jdd|_|jr.breaker_originalParseMethod)TT)_parserhasattr)r(rrr*rr+ set_break<s  zParserElement.set_break)fnsrLcOsZt|dgkrg|_n@tdd|Ds0tddd|D|_|d|dd |_|S) ao Define one or more actions to perform when successfully matching parse element definition. Parse actions can be called to perform data conversions, do extra validation, update external data structures, or enhance or replace the parsed tokens. Each parse action ``fn`` is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``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 :class:`ParseResults` object The parsed tokens are passed to the parse action as ParseResults. They can be modified in place using list-style append, extend, and pop operations to update the parsed list elements; and with dictionary-style item set and del operations to add, update, or remove any named results. If the tokens are modified in place, it is not necessary to return them with a return statement. Parse actions can also completely replace the given tokens, with another ``ParseResults`` object, or with some entirely different object (common for parse actions that perform data conversions). A convenient way to build a new parse result is to define the values using a dict, and then create the return value using :class:`ParseResults.from_dict`. If None is passed as the ``fn`` parse action, all previously added parse actions for this expression are cleared. Optional keyword arguments: - call_during_try = (default= ``False``) indicate if parse action should be run during lookaheads and alternate testing. For parse actions that have side effects, it is important to only call the parse action once it is determined that it is being called as part of a successful parse. For parse actions that perform additional validation, then call_during_try should be passed as True, so that the validation code is included in the preliminary "try" parses. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`parse_string` for more information on parsing strings containing ```` 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:: # parse dates in the form YYYY/MM/DD # use parse action to convert toks from str to int at parse time def convert_to_int(toks): return int(toks[0]) # use a parse action to verify that the date is a valid date def is_valid_date(instring, loc, toks): from datetime import date year, month, day = toks[::2] try: date(year, month, day) except ValueError: raise ParseException(instring, loc, "invalid date given") integer = Word(nums) date_str = integer + '/' + integer + '/' + integer # add parse actions integer.set_parse_action(convert_to_int) date_str.set_parse_action(is_valid_date) # note that integer fields are now ints, not strings date_str.run_tests(''' # successful parse - note that integer fields were converted to ints 1999/12/31 # fail - invalid date 1999/13/31 ''') Ncss|]}t|VqdSr&)callabler<rr*r*r+ sz1ParserElement.set_parse_action..zparse actions must be callablecSsg|] }t|qSr*rrr*r*r+r>sz2ParserElement.set_parse_action..call_during_tryrF)rrallrgetrr(rkwargsr*r*r+set_parse_actionSsK zParserElement.set_parse_actioncOs8|jdd|D7_|jp0|d|dd|_|S)z Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`. See examples in :class:`copy`. cSsg|] }t|qSr*rrr*r*r+r>sz2ParserElement.add_parse_action..rrF)rrrrr*r*r+add_parse_actions   zParserElement.add_parse_actionc OsN|D](}|jt||d|dddq|jpF|d|dd|_|S)aAdd a boolean predicate function to expression's list of parse actions. See :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``, functions passed to ``add_condition`` 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 - call_during_try = boolean to indicate if this method should be called during internal tryParse calls, default=False Example:: integer = Word(nums).set_parse_action(lambda toks: int(toks[0])) year_int = integer.copy() year_int.add_condition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parse_string("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) rrF)rrrr)rrrrr)r(rrrr*r*r+ add_conditions   zParserElement.add_condition)rrLcCs ||_|S)a Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments ``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 :class:`ParseFatalException` if it is desired to stop parsing immediately.)r)r(rr*r*r+set_fail_actions zParserElement.set_fail_actionc CsNd}|rJd}|jD]4}z|||\}}d}qWqtk rDYqXqq|SNTF)rrr)r(rr exprsFoundedummyr*r*r+_skipIgnorabless   zParserElement._skipIgnorablescCsH|jr|||}|jrDt|}|j}||krD|||krD|d7}q&|SNr)rrrlenr)r(rrinstrlen white_charsr*r*r+preParses  zParserElement.preParsecCs|gfSr&r*r(rrrr*r*r+ parseImplszParserElement.parseImplcCs|Sr&r*r(rr tokenlistr*r*r+ postParseszParserElement.postParsec Csxd\}}}|j}t|} |s$|jrz|r>|jr>|||} n|} | } |jjr`|j|| |d|jsn| | krz||| |\}} Wqt k rt || |j |YqXn||| |\}} WnZt k r} z:|jj r|j || || d|jr||| || W5d} ~ XYnXn|r:|jr:|||} n|} | } |jsT| | krz||| |\}} Wn&t k rt || |j |YnXn||| |\}} |||| } t| |j|j|jd}|jrJ|s|jrJ|rz|jD]}z||| |} Wn2t k r4}zt d}||W5d}~XYnX| dk r| |k rt| |j|joft| ttf|jd}qWnDt k r} z$|jj r|j || || dW5d} ~ XYnXn|jD]}z||| |} Wn2t k r }zt d}||W5d}~XYnX| dk r| |k rt| |j|jorrLr*r*r+enable_packrats    zParserElement.enable_packrat)parseAll)r parse_allrPrLc Cs|p|}t|js||jD] }|q$|js@|}z<||d\}}|rz|||}t t }|||Wn6t k r}ztj rn | dW5d}~XYnX|SdS)a6 Parse a string with respect to the parser definition. This function is intended as the primary interface to the client code. :param instring: The input string to be parsed. :param parse_all: If set, the entire input string must match the grammar. :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release. :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar. :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or an object with attributes if the given parser includes results names. If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This is also equivalent to ending the grammar with :class:`StringEnd`(). To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string being parsed, one can ensure a consistent view of the input string by doing one of the following: - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`), - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the parse action's ``s`` argument, or - explicitly expand the tabs in your input string before calling ``parse_string``. Examples: By default, partial matches are OK. >>> res = Word('a').parse_string('aaaaabaaa') >>> print(res) ['aaaaa'] The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children directly to see more examples. It raises an exception if parse_all flag is set and instring does not match the whole grammar. >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True) Traceback (most recent call last): ... pyparsing.ParseException: Expected end of text, found 'b' (at char 5), (line:1, col:6) rN)rur@r streamlinerr expandtabsrrEmpty StringEndr5rwith_traceback) r(rrQrPr rr&serr*r*r+ parse_string4s&-    zParserElement.parse_string)r maxMatches)r max_matchesoverlaprrYrLc csht||}|js||jD] }|q|js>t|}t|}d}|j} |j } t d} z||kr&| |kr&z | ||} | || dd\} }Wnt k r| d}YqdX| |kr| d7} |rt || | d|| | fV|r| ||}||kr | }n|d7}n| }qd| d}qdWn:tk rb}zt jrHn |dW5d}~XYnXdS)at Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional ``max_matches`` argument, to clip scanning after 'n' matches are found. If ``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 :class:`parse_string` for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens, start, end in Word(alphas).scan_string(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd rFrr)r&startendN)minrrRrrstrrSrrrru resetCacherrrr5rrV)r(rrZr[rrYr rr preparseFnparseFnmatchesprelocnextLocr&nextlocrr*r*r+ scan_stringysR'          zParserElement.scan_stringr)rrrLc Csg}d}d|_z|j||dD]f\}}}|||||rt|trV||7}n*t|trvt|tsv||n |||}q|||ddd|D}d ddt |DWSt k r}zt j rڂn |dW5d}~XYnXdS) ab Extension to :class:`scan_string`, to modify matching text with modified tokens that may be returned from a parse action. To use ``transform_string``, define a grammar and attach a parse action to it that modifies the returned token list. Invoking ``transform_string()`` on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. ``transform_string()`` returns the resulting transformed string. Example:: wd = Word(alphas) wd.set_parse_action(lambda toks: toks[0].title()) print(wd.transform_string("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. rTriNcSsg|] }|r|qSr*r*r<or*r*r+r>sz2ParserElement.transform_string..rkcSsg|] }t|qSr*r`)r<r}r*r*r+r>s)rrhrrrrrr"extendjoinrr5rurrV) r(rroutlastErr}r rr*r*r+transform_strings(   zParserElement.transform_string)rrZrrYrLc Csft||}z tdd|j|||dDWStk r`}ztjrFn |dW5d}~XYnXdS)a Another extension to :class:`scan_string`, simplifying the access to the tokens found to match the given parse expression. May be called with optional ``max_matches`` 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.search_string("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.search_string("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|]\}}}|qSr*r*)r<rr}r r*r*r+r>sz/ParserElement.search_string..riN)r_rrhr5rurrV)r(rrZrrYrr*r*r+ search_strings zParserElement.search_string)includeSeparators)rmaxsplitinclude_separatorsrLc csX|p|}d}|j||dD]*\}}}|||V|r@|dV|}q||dVdS)aT Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``include_separators`` argument (default= ``False``), if the separating matching text should be included in the split results. Example:: punc = one_of(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] r)rZN)rh) r(rrtrurslastrr}r r*r*r+rD(s zParserElement.splitcCsN|tkrt|St|tr$||}t|tsBtdt|j t ||gS)ah Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement` converts them to :class:`Literal`s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print(hello, "->", greet.parse_string(hello)) prints:: Hello, World! -> ['Hello', ',', 'World', '!'] ``...`` may be used as a parse expression as a short form of :class:`SkipTo`. Literal('start') + ... + Literal('end') is equivalent to: Literal('start') + SkipTo('end')("_skipped*") + Literal('end') Note that the skipped text is returned with '_skipped' as a results name, and to support having multiple skips in the same parser, the value returned is a list of all skipped text. 4Cannot combine element of type {} with ParserElement) Ellipsis _PendingSkiprr"rrurrrr.Andr(otherr*r*r+__add__Hs   zParserElement.__add__cCsR|tkrt|d|St|tr,||}t|tsJtdt|j ||S)zd Implementation of ``+`` operator when left operand is not a :class:`ParserElement` _skipped*rw) rxSkipTorr"rrurrrr.r{r*r*r+__radd__ps   zParserElement.__radd__cCsBt|tr||}t|ts2tdt|j|t |S)zX Implementation of ``-`` operator, returns :class:`And` with error stop rw) rr"rrurrrr.rz _ErrorStopr{r*r*r+__sub__s   zParserElement.__sub__cCs:t|tr||}t|ts2tdt|j||S)zd Implementation of ``-`` operator when left operand is not a :class:`ParserElement` rwrr"rrurrrr.r{r*r*r+__rsub__s   zParserElement.__rsub__cs$|tkrd}n8t|trF|ddtfkrFd|ddddd}t|tr^|d}}nt|trRtdd |D}|d dd}|ddkrd|df}t|dtr|ddkr|ddkrtS|ddkrtS|dtSnPt|dtr2t|dtr2|\}}||8}ntd d d d |Dntdt |j |dkrxt d|dkrt d||krdkrnnt gS|rfdd|r|dkr|}nt g||}n|}n|dkr}nt g|}|S)a Implementation of ``*`` operator, allows use of ``expr * 3`` in place of ``expr + expr + expr``. Expressions may also be multiplied by a 2-integer tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples may also include ``None`` as in: - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent to ``expr*n + ZeroOrMore(expr)`` (read as "at least n instances of ``expr``") - ``expr*(None, n)`` is equivalent to ``expr*(0, n)`` (read as "0 to n instances of ``expr``") - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)`` - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)`` Note that ``expr*(None, n)`` does not raise an exception if more than n exprs exist in the input stream; that is, ``expr*(None, n)`` does not enforce a maximum number of expr occurrences. If this behavior is desired, then write ``expr*(None, n) + ~expr`` )rNNr)rr&r\rcss|]}|tk r|ndVqdSr&)rxrjr*r*r+rsz(ParserElement.__mul__..)NNz.cannot multiply ParserElement and ({}) objects,css|]}t|jVqdSr&rr.)r<itemr*r*r+rsz,cannot multiply ParserElement and {} objectsz/cannot multiply ParserElement by negative valuez@second tuple value must be greater or equal to first tuple valuecs(|dkrt|dStSdSr)Opt)nmakeOptionalListr(r*r+rsz/ParserElement.__mul__..makeOptionalList) rxrtupleint ZeroOrMore OneOrMorerrrnrr. ValueErrorrz)r(r| minElements optElementsr1r*rr+__mul__sb             zParserElement.__mul__cCs ||Sr&)rr{r*r*r+__rmul__szParserElement.__rmul__cCsR|tkrt|ddSt|tr(||}t|tsFtdt|j t ||gS)zP Implementation of ``|`` operator - returns :class:`MatchFirst` T) must_skiprw) rxryrr"rrurrrr. MatchFirstr{r*r*r+__or__s    zParserElement.__or__cCs:t|tr||}t|ts2tdt|j||BS)zd Implementation of ``|`` operator when left operand is not a :class:`ParserElement` rwrr{r*r*r+__ror__s   zParserElement.__ror__cCs>t|tr||}t|ts2tdt|jt||gS)zH Implementation of ``^`` operator - returns :class:`Or` rw) rr"rrurrrr.Orr{r*r*r+__xor__s   zParserElement.__xor__cCs:t|tr||}t|ts2tdt|j||AS)zd Implementation of ``^`` operator when left operand is not a :class:`ParserElement` rwrr{r*r*r+__rxor__#s   zParserElement.__rxor__cCs>t|tr||}t|ts2tdt|jt||gS)zJ Implementation of ``&`` operator - returns :class:`Each` rw) rr"rrurrrr.Eachr{r*r*r+__and__1s   zParserElement.__and__cCs:t|tr||}t|ts2tdt|j||@S)zd Implementation of ``&`` operator when left operand is not a :class:`ParserElement` rwrr{r*r*r+__rand__?s   zParserElement.__rand__cCst|S)zL Implementation of ``~`` operator - returns :class:`NotAny` )NotAnyr(r*r*r+ __invert__MszParserElement.__invert__cCszt|tr|f}t|Wntk r8||f}YnXt|dkrxtd|ddt|dkrpdt|nd|t|dd}|S)a{ use ``[]`` indexing notation as a short form for expression repetition: - ``expr[n]`` is equivalent to ``expr*n`` - ``expr[m, n]`` is equivalent to ``expr*(m, n)`` - ``expr[n, ...]`` or ``expr[n,]`` is equivalent to ``expr*n + ZeroOrMore(expr)`` (read as "at least n instances of ``expr``") - ``expr[..., n]`` is equivalent to ``expr*(0, n)`` (read as "0 to n instances of ``expr``") - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)`` - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)`` ``None`` may be used in place of ``...``. Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception if more than ``n`` ``expr``s exist in the input stream. If this behavior is desired, then write ``expr[..., n] + ~expr``. r\z,only 1 or 2 index arguments supported ({}{})Nr^z... [{}]rk)rr"iterrrrr)r(keyr1r*r*r+ __getitem__Ws    zParserElement.__getitem__)rJrLcCs|dk r||S|SdS)a Shortcut for :class:`set_results_name`, with ``list_all_matches=False``. If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be passed as ``True``. If ``name` is omitted, same as calling :class:`copy`. Example:: # these are equivalent userdata = Word(alphas).set_results_name("name") + Word(nums + "-").set_results_name("socsecno") userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") N)rrr(rJr*r*r+__call__s zParserElement.__call__cCst|S)z Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output. )Suppressrr*r*r+suppressszParserElement.suppress recursiverLcCs d|_|S)z Enables the skipping of whitespace before matching the characters in the :class:`ParserElement`'s defined pattern. :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any) Trr(rr*r*r+ignore_whitespaceszParserElement.ignore_whitespacecCs d|_|S)a| Disables the skipping of whitespace before matching the characters in the :class:`ParserElement`'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. :param recursive: If true (the default), also disable whitespace skipping in child elements (if any) Frrr*r*r+leave_whitespaceszParserElement.leave_whitespace)r copy_defaultsrLcCsd|_t||_||_|S)z8 Overrides the default whitespace chars T)rrrr)r(rrr*r*r+set_whitespace_charss z"ParserElement.set_whitespace_charscCs d|_|S)z Overrides default behavior to expand ```` s to spaces before parsing the input string. Must be called before ``parse_string`` when the input grammar contains elements that match ```` characters. T)rrr*r*r+parse_with_tabsszParserElement.parse_with_tabs)r|rLcCsTddl}t|trt|}t|tr<||jkrP|j|n|jt||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 = Word(alphas)[1, ...] patt.parse_string('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(c_style_comment) patt.parse_string('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] rN)rrr"rrrr)r(r|rr*r*r+ignores   zParserElement.ignore) start_actionsuccess_actionexception_actionrLcCs&||p t|pt|pt|_d|_|S)a  Customize display of debugging messages while doing pattern matching: - ``start_action`` - method to be called when an expression is about to be parsed; should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)`` - ``success_action`` - method to be called when an expression has successfully parsed; should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)`` - ``exception_action`` - method to be called when expression fails to parse; should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)`` T)rrrrrr)r(rrrr*r*r+set_debug_actionsszParserElement.set_debug_actions)flagrLcCs|r|tttnd|_|S)a Enable display of debugging messages while doing pattern matching. Set ``flag`` to ``True`` to enable, ``False`` to disable. Example:: wd = Word(alphas).set_name("alphaword") integer = Word(nums).set_name("numword") term = wd | integer # turn on debugging for wd wd.set_debug() term[1, ...].parse_string("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 :class:`set_debug_actions`. Prior to attempting to match the ``wd`` expression, the debugging message ``"Match at loc (,)"`` is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"`` message is shown. Also note the use of :class:`set_name` 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 :class:`Word` expression without calling ``set_name`` is ``"W:(A-Za-z)"``. F)rrrrr)r(rr*r*r+ set_debugs%zParserElement.set_debugcCs|jdkr||_|jSr&)r_generateDefaultNamerr*r*r+ default_name(s  zParserElement.default_namecCsdS)zg Child classes must define this method, which defines how the ``default_name`` is set. Nr*rr*r*r+r.sz"ParserElement._generateDefaultNamecCs$||_d|j|_tjr ||S)a\ Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parse_string("ABC") # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1) Word(nums).set_name("integer").parse_string("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) Expected )rrJrrFrXrrr*r*r+set_name4s  zParserElement.set_namecCs|jdk r|jS|jSr&)rrrr*r*r+rJAszParserElement.namecCs|jSr&rJrr*r*r+__str__FszParserElement.__str__cCst|Sr&rlrr*r*r+__repr__IszParserElement.__repr__cCsd|_d|_|SNT)rrrr*r*r+rRLszParserElement.streamlinecCsgSr&r*rr*r*r+recurseQszParserElement.recursecCs.|dd|g}|D]}||qdSr&)r_checkRecursionr(parseElementListsubRecCheckListr r*r*r+rTs zParserElement._checkRecursioncCs|gdS)zj Check defined expressions for valid structure, check for infinite recursive definitions. N)r)r( validateTracer*r*r+validateYszParserElement.validateutf-8)file_or_filenameencodingrQrPrLc Cs|p|}z |}Wn6tk rJt|d|d}|}W5QRXYnXz|||WStk r}ztjrvn |dW5d}~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. rrN)readAttributeErroropenrXr5rurrV)r(rrrQrP file_contentsfrr*r*r+ parse_file_s  zParserElement.parse_filecCsB||kr dSt|tr$|j|ddSt|tr>t|t|kSdS)NTrQF)rr"rdruvarsr{r*r*r+__eq__{s  zParserElement.__eq__cCst|Sr&)idrr*r*r+__hash__szParserElement.__hash__) test_stringrQrPrLcCs<|o|}z|jt||dWdStk r6YdSXdS)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: - ``test_string`` - to test against this expression for a match - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests Example:: expr = Word(nums) assert expr.matches("100") rTFN)rXr`r5)r(rrQrPr*r*r+rds zParserElement.matches#)rPfullDump printResults failureTestsr)testsrQcomment full_dump print_results failure_tests post_parsefilewith_line_numbersrPrrrrrLc  s4ddlm}| o|} | o|} | o"|} | p*|} |p2|}t|trbt|jfdd|D}t|trtt|}|dkrt j }|j }g}g}d}td t dt}d }|D]t}|dk r||d s|r|s|| r||n|q|sq|r dd|nd | r||n|g}g}z"|||}|j|| d }Wntk r}z`t|trld nd }|||dt|tjr|t|j |o| }|}W5d}~XYn4t!k r,}zD|d"t|j#|tjr|t|j |o| }|}W5d}~XYnX|o8| }|dk rzR|||}|dk rt|t$rv||%n|t|n||%WnRt!k r}z2||j%| d|d"|j#t|j#|W5d}~XYnXn||j%| d|d | r|d||||fq||fS)a 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 - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline; if False, only dump nested list - ``print_results`` - (default= ``True``) prints test output to stdout - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as `fn(test_string, parse_results)` and returns a string to be added to the test output - ``file`` - (default= ``None``) optional file-like object to which test output will be written; if None, will default to ``sys.stdout`` - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if ``failure_tests`` 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.run_tests(''' # 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.run_tests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failure_tests=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.run_tests(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'``.) r)pyparsing_testcsg|] }|qSr*r*)r< test_line line_stripr*r+r>sz+ParserElement.run_tests..NT\n uFrkrz(FATAL)zFAIL: zFAIL-EXCEPTION: {}: {})fullz{} failed: {}: {})&testingrrr"rstriprstrip splitlinesLiteralsysstdoutwriter replace_withr quoted_stringrdrrrnrqlstriprXr5rexplainr`rurrmr format_tbrrrr.rdump)r(rrQrrrrrrrrPrrrrrprint_ allResultscommentssuccessNLBOMrror=r;rrpp_valuer r*rr+ run_testssp             zParserElement.run_testsr#) output_htmlverticalshow_results_names show_groupsrLc Kszddlm}m}Wn,tk r@}ztd|W5d}~XYnX|||||||d} t|ttfrt |ddd} | || W5QRXn| || dS) a Create a railroad diagram for the parser. Parameters: - output_html (str or file-like object) - output target for generated diagram HTML - vertical (int) - threshold for formatting multiple alternatives vertically instead of horizontally (default=3) - show_results_names - bool flag whether diagram should show annotations for defined results names - show_groups - bool flag whether groups should be highlighted with an unlabeled surrounding box Additional diagram-formatting keyword arguments can also be included; see railroad.Diagram class. r) to_railroadrailroad_to_htmlzMmust ``pip install pyparsing[diagrams]`` to generate parser railroad diagramsN)rrrdiagram_kwargswrr) diagramrr ImportErrorrrRrr`rrr) r(rrrrrrrierailroad diag_filer*r*r+create_diagramas(zParserElement.create_diagram)F)F)F)T)T)TT)F)TT)N)rN)F)N)T)T)F)T)N)rF)T)TrTTFNNF)r#FF)r.r3r4r?rr`rrrlrrrr staticmethodrrrrr,r[rrrrr ParseActionrrParseConditionrParseFailActionr rrrrrrrr*r-r.rrecursion_lockr0Dictrrr2r1r4r>rr@rBrArCrMrOrX_MAX_INTrrhrqrrrDr}rrrrrrrrrrrr__iter__rrrrrr rrrrrrrrpropertyrr rrrJrrrRr rrrrr rrrrdrrrrsetDefaultWhitespaceCharsinlineLiteralsUsingsetResultsNamesetBreaksetParseActionaddParseAction addCondition setFailActiontryParse canParseNextraenableLeftRecursion enablePackrat parseString scanString searchStringtransformStringsetWhitespaceChars parseWithTabssetDebugActionssetDebug defaultNamesetName parseFilerunTestsignoreWhitespaceleaveWhitespacer*r*r*r+rus    ! V #   f   0 /, H Y1 + (V(     /         G  .csLeZdZdeedfdd ZddZddd d Zd d Zd dZ Z S)ryF)rrcst||_||_dSr&)superr,anchorr)r(rrrr*r+r,s z_PendingSkip.__init__cCst|jtddS)NrT...)r`r4rTreplacerr*r*r+rsz!_PendingSkip._generateDefaultNamerurKcs\t|dd}jrNdd}fdd}j||||B|Sj||S)Nr6r~cSs,|jr|jdgkr(|d=|dddS)Nrkr_skipped)r8rpoprr*r*r+rsz'_PendingSkip.__add__..must_skipcs<|jdddgkr8|ddtjd|d<dS)Nrrkr8z missing <>)r8rr9reprr4r:rr*r+ show_skips z'_PendingSkip.__add__..show_skip)rrrr4r)r(r|skipperrr=r*rr+r}s  z_PendingSkip.__add__cCs|jSr&)r-rr*r*r+rsz_PendingSkip.__repr__cGs tddS)NzBuse of `...` expression without following SkipTo target expression)r)r(rr*r*r+rsz_PendingSkip.parseImpl)F) r.r3r4rurlr,rr}rr __classcell__r*r*r5r+rys rycs(eZdZdZfddZddZZS)TokenzYAbstract :class:`ParserElement` subclass, for defining atomic matching patterns. cstjdddS)NFrr3r,rr5r*r+r,szToken.__init__cCs t|jSr&rrr*r*r+rszToken._generateDefaultName)r.r3r4r?r,rr?r*r*r5r+r@s r@cs eZdZdZfddZZS)rTz, An empty token, will always match. cstd|_d|_dSr r3r,rrrr5r*r+r,s zEmpty.__init__)r.r3r4r?r,r?r*r*r5r+rTsrTcs*eZdZdZfddZdddZZS)NoMatchz( A token that will never match. cs td|_d|_d|_dS)NTFzUnmatchable token)r3r,rrrrr5r*r+r,s zNoMatch.__init__TcCst|||j|dSr&)rrrr*r*r+rszNoMatch.parseImpl)Tr.r3r4r?r,rr?r*r*r5r+rCs rCcsBeZdZdZd ddeedfddZddZd d d ZZS)ra Token to exactly match a specified string. Example:: Literal('blah').parse_string('blah') # -> ['blah'] Literal('blah').parse_string('blahfooblah') # -> ['blah'] Literal('blah').parse_string('bla') # -> Exception: Expected "blah" For case-insensitive matching, use :class:`CaselessLiteral`. For keyword matching (force word break before and after the matched string), use :class:`Keyword` or :class:`CaselessKeyword`. rk matchString match_stringrFcst|p|}||_t||_z|d|_Wntk rLtdYnXd|j|_ d|_ d|_ |jdkrt |t krt|_dS)Nrz2null string passed to Literal; use Empty() insteadrFr)r3r,matchrmatchLenfirstMatchCharrrrJrrrrr_SingleCharLiteralrr(rHrFr5r*r+r, s   zLiteral.__init__cCs t|jSr&r<rIrr*r*r+r szLiteral._generateDefaultNameTcCs@|||jkr,||j|r,||j|jfSt|||j|dSr&)rKr:rIrJrrrr*r*r+r s zLiteral.parseImpl)rk)T) r.r3r4r?r`r,rrr?r*r*r5r+rsrc@seZdZdddZdS)rLTcCs0|||jkr|d|jfSt|||j|dSr)rKrIrrrr*r*r+r) sz_SingleCharLiteral.parseImplN)Tr.r3r4rr*r*r*r+rL( srLcsteZdZdZedZddddeejee eejedfdd Z d d Z dd dZ e ddddZeZZS)Keyworda Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with :class:`Literal`: - ``Literal("if")`` will match the leading ``'if'`` in ``'ifAndOnlyIf'``. - ``Keyword("if")`` will not; it will only match the leading ``'if'`` in ``'if x=1'``, or ``'if(y==2)'`` Accepts two optional constructor arguments in addition to the keyword string: - ``identChars`` is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + "_" and "$" - ``caseless`` allows case-insensitive matching, default is ``False``. Example:: Keyword("start").parse_string("start") # -> ['start'] Keyword("start").parse_string("starting") # -> Exception For case-insensitive matching, use :class:`CaselessKeyword`. z_$rkNFrF identChars)rH ident_charscaselessrFrRcst|p|}|dkr tj}|p&|}||_t||_z|d|_Wntk rbt dYnXd t |j |j |_d|_d|_||_|r||_|}t||_dS)Nrz2null string passed to Keyword; use Empty() insteadzExpected {} {}F)r3r,rPDEFAULT_KEYWORD_CHARSrIrrJrKrrrrr.rJrrrrTupper caselessmatchrrR)r(rHrSrTrFrRr5r*r+r,O s&   zKeyword.__init__cCs t|jSr&rNrr*r*r+rl szKeyword._generateDefaultNameTcCs^|j}|}|jr||||j|jkr|dksJ||d|jkr|t||jkst|||j|jkr||j|jfS|d7}||j}n|d7}|d}n|||jkr|jdks| |j|rL|dks||d|jkr<|t||jks|||j|jkr(||j|jfS|d7}||j}n|d7}|d}t ||||dS)Nrrz/, was immediately followed by keyword characterz7, keyword was immediately preceded by keyword characterz7, keyword was immediately followed by keyword character) rrTrJrVrWrRrrIrKr:r)r(rrrrerrlocr*r*r+ro sB     zKeyword.parseImplrKcCs |t_dS)zX Overrides the default characters used by :class:`Keyword` expressions. N)rPrU)rr*r*r+set_default_keyword_chars sz!Keyword.set_default_keyword_chars)rkNF)T)r.r3r4r? alphanumsrUr`rrrlr,rrrrYsetDefaultKeywordCharsr?r*r*r5r+rP2 s( /rPcs:eZdZdZd ddeedfddZd dd ZZS) CaselessLiteralaq 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:: CaselessLiteral("CMD")[1, ...].parse_string("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] (Contrast with example for :class:`CaselessKeyword`.) rkrErGcs.|p|}t|||_d|j|_dS)Nr)r3r,rV returnStringrJrrMr5r*r+r, szCaselessLiteral.__init__TcCs@||||j|jkr,||j|jfSt|||j|dSr&)rJrVrIr]rrrr*r*r+r szCaselessLiteral.parseImpl)rk)T)r.r3r4r?r`r,rr?r*r*r5r+r\ s r\csBeZdZdZddddeejeeejedfddZZS) CaselessKeywordz Caseless version of :class:`Keyword`. Example:: CaselessKeyword("CMD")[1, ...].parse_string("cmd CMD Cmd10") # -> ['CMD', 'CMD'] (Contrast with example for :class:`CaselessLiteral`.) rkNrQ)rHrSrFrRcs&|p|}|p|}tj||dddS)NT)rTrA)r(rHrSrFrRr5r*r+r, szCaselessKeyword.__init__)rkN) r.r3r4r?r`rrr,r?r*r*r5r+r^ s r^csFeZdZdZddddeeedfddZd d Zdd d ZZ S) CloseMatchaA variation on :class:`Literal` which matches "close" matches, that is, strings with at most 'n' mismatching characters. :class:`CloseMatch` takes parameters: - ``match_string`` - string to be matched - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters - ``max_mismatches`` - (``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: - ``mismatches`` - a list of the positions within the match_string where mismatches were found - ``original`` - the original match_string used to compare against the input string If ``mismatches`` is an empty list, then the match was an exact match. Example:: patt = CloseMatch("ATCATCGAATGGA") patt.parse_string("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) patt.parse_string("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) # exact match patt.parse_string("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) # close match allowing up to 2 mismatches patt = CloseMatch("ATCATCGAATGGA", max_mismatches=2) patt.parse_string("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) NrF) maxMismatchesrT)rHmax_mismatchesr`csN|dk r |n|}t||_||_d|j|j|_||_d|_d|_dS)Nz(Expected {!r} (with up to {} mismatches)F) r3r,rHr`rrrTrr)r(rHrar`rTr5r*r+r, s zCloseMatch.__init__cCsdt|j|jS)Nz{}:{!r})rrr.rHrr*r*r+r szCloseMatch._generateDefaultNameTcCs|}t|}|t|j}||kr|j}d}g} |j} tt||||D]J\}} | \} } |jrt| | } } | | krL| |t| | krLqqL||d}t|||g}||d<| |d<||fSt |||j |dS)Nrroriginal mismatches) rrHr` enumerateziprTrmrrrr)r(rrrr]rmaxlocrHmatch_stringlocrcr`s_msrcmatresultsr*r*r+r s0    zCloseMatch.parseImpl)N)T r.r3r4r?r`rr,rrr?r*r*r5r+r_ s%r_csxeZdZdZddddddeejeeeeeejeejeejeeejed fd d Z d d Z dddZ Z S)Worda8 Token for matching words composed of allowed character sets. Parameters: - ``init_chars`` - string of all characters that should be used to match as a word; "ABC" will match "AAA", "ABAB", "CBAC", etc.; if ``body_chars`` is also specified, then this is the string of initial characters - ``body_chars`` - string of characters that can be used for matching after a matched initial character as given in ``init_chars``; if omitted, same as the initial characters (default=``None``) - ``min`` - minimum number of characters to match (default=1) - ``max`` - maximum number of characters to match (default=0) - ``exact`` - exact number of characters to match (default=0) - ``as_keyword`` - match as a keyword (default=``False``) - ``exclude_chars`` - characters that might be found in the input ``body_chars`` string but which should not be accepted for matching ;useful to define a word of all printables except for one or two characters, for instance (default=``None``) :class:`srange` is useful for defining custom character set strings for defining :class:`Word` expressions, using range notation from regular expression character sets. A common mistake is to use :class:`Word` to match a specific literal string, as in ``Word("Address")``. Remember that :class:`Word` uses the string argument to define *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 :class:`Literal` or :class:`Keyword`. pyparsing includes helper strings for building Words: - :class:`alphas` - :class:`nums` - :class:`alphanums` - :class:`hexnums` - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.) - :class:`punc8bit` (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.) - :class:`printables` (any non-whitespace character) ``alphas``, ``nums``, and ``printables`` are also defined in several Unicode sets - see :class:`pyparsing_unicode``. 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, exclude_chars=",") rkNrrF) initChars bodyChars asKeyword excludeChars) init_chars body_charsr_maxexact as_keyword exclude_charsrnrorprqc s|p|}| p|} | p|} | p|} t|sBtdt|jt|}||_| rtt| } || 8}| rtt| | } dt ||_ | rdt | |_ t| |_ ndt ||_ t||_ |dk|_ |dkrtd||_|dkr||_nt|_|dkr ||_||_d|j|_d|_| |_d|j|j Bkr|dkr|dkr|j |jkr|dkrfd } n0|dkrvd} n d |j|jtkrdn|j} d t|j| |_nt|jdkr|dkrd } nd |d} dt|j t|j | |_nJ|dkr d } n|dkrd} nd |d} dt|jt|j | |_|jr\d|jd|_zt|j|_Wntjk rd|_YnX|jj|_t|_dS)Nz,invalid {}, initChars cannot be empty stringrkrrzUcannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permittedrFr+ {{{},{}}}z[{}]{}rz{{0,{}}}z{}[{}]{}r\z [{}][{}]{}z\b) r3r,rrrr.rrnrnsorted initCharsOrig bodyCharsOrigro maxSpecifiedminLenmaxLenrrJrrrprreStringrreescapecompileerrorrIre_match _WordRegexr) r(rrrsr_rtrurvrwrnrorprqrepeatr5r*r+r,v s       &        z Word.__init__cCsdd}|j|jkr.d||j||j}nd||j}|jdksR|jtkr|j|jkr|jdkrt|ddS|d|jSn.|jtkr|d|jS|d |j|jS|S) NcSs8d}t|dd}t||kr0|d|ddS|SdS)NF) re_escaper#r6)rr)r} max_repr_lenr*r*r+ charsAsStr s   z-Word._generateDefaultName..charsAsStrz W:({}, {})zW:({})rr\z{{{}}}z {{{},...}}ry)rnrorr~rr)r(rbaser*r*r+r s      zWord._generateDefaultNameTc Cs|||jkrt|||j||}|d7}t|}|j}||j}t||}||krj|||krj|d7}qLd}|||jkrd}nV|jr||kr|||krd}n6|j r|dkr||d|ks||kr|||krd}|rt|||j|||||fS)NrFTr) rnrrrrorr_r~r}rp) r(rrrr]r bodycharsrfthrowExceptionr*r*r+r s8    zWord.parseImpl)rkNrrrFN)T) r.r3r4r?r`rrrrlr,rrr?r*r*r5r+rm5 s8B qrmc@seZdZdddZdS)rTcCs4|||}|s t|||j||}||fSr&)rrrr^group)r(rrrr=r*r*r+r& s  z_WordRegex.parseImplN)TrOr*r*r*r+r% srcsDeZdZdZddddeeejeeejedfddZZ S) CharzA short-cut class for defining :class:`Word` ``(characters, exact=1)``, when defining a match of any single character in a string of characters. FN)rprq)charsetrvrwrprqcsd|p|}|p|}tj|d||ddt|j|_|rHd|j|_t|j|_|jj|_ dS)Nr)rurprqz[{}]z\b{}\b) r3r,rrrnrrrrIr)r(rrvrwrprqr5r*r+r,5 s z Char.__init__)FN) r.r3r4r?r`rlrrr,r?r*r*r5r+r/ src seZdZdZddddeeejefe e e e dfddZ e dd Ze d d Z e d d Z ddZdddZdddZdddZeedddZZS)RegexaToken for matching strings that match a given regular expression. Defined with string specifying the regular expression in a form recognized by the stdlib Python `re module `_. If the given regex contains named groups (defined using ``(?P...)``), these will be preserved as named :class:`ParseResults`. If instead of the Python stdlib ``re`` module you wish to use a different RE module (such as the ``regex`` module), you can do so by building your ``Regex`` object with a compiled RE that was compiled using ``regex``. Example:: realnum = Regex(r"[+-]?\d+\.\d*") # ref: https://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?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") # named fields in a regex will be returned as named results date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') # the Regex class will accept re's compiled using the regex module import regex parser = pp.Regex(regex.compile(r'[0-9]')) rF) asGroupListasMatch)patternflags as_group_listas_matchrrcst|p|}|p|}t|trJ|s0tdd|_||_|_||_n8t |drzt |drz||_|j|_|_||_nt dd|j |_ d|_ ||_||_|jr|j|_|jr|j|_dS)aThe parameters ``pattern`` and ``flags`` are passed to the ``re.compile()`` function as-is. See the Python `re module `_ module for an explanation of the acceptable patterns and flags. z0null string passed to Regex; use Empty() insteadNrrIzCRegex may only be constructed with a string or a compiled RE objectrF)r3r,rr"r_rerrrrrrJrrrrparseImplAsGroupListrparseImplAsMatch)r(rrrrrrr5r*r+r,c s0    zRegex.__init__cCsJ|jr |jSzt|j|jWStjk rDtd|jYnXdS)Nz&invalid pattern ({!r}) passed to Regex)rrrrrrrrrr*r*r+r s zRegex.recCs|jjSr&)rrIrr*r*r+r szRegex.re_matchcCs|ddk SNrk)rrr*r*r+r szRegex.mayReturnEmptycCsdt|jddS)NzRe:({})z\\\)rr<rr7rr*r*r+r szRegex._generateDefaultNameTc Csb|||}|s t|||j||}t|}|}|rZ|D]\}}|||<qH||fSr&)rrrr^rr groupdictitems) r(rrrr=r1dkvr*r*r+r s   zRegex.parseImplcCs8|||}|s t|||j||}|}||fSr&)rrrr^groupsr(rrrr=r1r*r*r+r s  zRegex.parseImplAsGroupListcCs4|||}|s t|||j||}|}||fSr&)rrrr^rr*r*r+r s  zRegex.parseImplAsMatch)replrLcsPjrtdjr$tr$tdjr8fdd}nfdd}|S)a Return :class:`Regex` with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) `_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2") print(make_html.transform_string("h1:main title:")) # prints "

main title

" z-cannot use sub() with Regex(asGroupList=True)z9cannot use sub() with a callable with Regex(asMatch=True)cs|dSr)expandr&)rr*r+r szRegex.sub..pacsj|dSr)rsubrrr(r*r+r s)rrrrr)r(rrr*rr+r s z Regex.sub)rFF)T)T)T)r.r3r4r?rrr RegexFlagrrlr,r%rrrrrrr`rurr?r*r*r5r+rJ s4 .    rcseZdZdZdZddddddddeejeejeeeejeeeejeejeeejeed fd d Z d d Z dd dZ Z S) QuotedStringa Token for matching strings that are delimited by quoting characters. Defined with the following parameters: - ``quote_char`` - string of one or more characters defining the quote delimiting string - ``esc_char`` - character to re_escape quotes, typically backslash (default= ``None``) - ``esc_quote`` - special quote sequence to re_escape an embedded quote string (such as SQL's ``""`` to re_escape an embedded ``"``) (default= ``None``) - ``multiline`` - boolean indicating whether quotes can span multiple lines (default= ``False``) - ``unquote_results`` - boolean indicating whether the matched text should be unquoted (default= ``True``) - ``end_quote_char`` - string of one or more characters defining the end of the quote delimited string (default= ``None`` => same as quote_char) - ``convert_whitespace_escapes`` - convert escaped whitespace (``'\t'``, ``'\n'``, etc.) to actual whitespace (default= ``True``) Example:: qs = QuotedString('"') print(qs.search_string('lsjdf "This is the quote" sldjf')) complex_qs = QuotedString('{{', end_quote_char='}}') print(complex_qs.search_string('lsjdf {{This is the "quote"}} sldjf')) sql_qs = QuotedString('"', esc_quote='""') print(sql_qs.search_string('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']] ))z\t )rr)z\f )z\r rkNFT) quoteCharescCharescQuoteunquoteResults endQuoteCharconvertWhitespaceEscapes) quote_charesc_char esc_quote multilineunquote_resultsend_quote_charconvert_whitespace_escapesrrrrrrc sft| p|} | p|} | o |} | p(|} | o0|} |p8|}|}|sNtd| dkr\|} n| } | sptd|_t|_|d_| _t| _ | _ | _ | _ | _ d}d}| r|d|t| 7}d}| r |d|t| 7}d}tj d_tjd krZ|d |dfd d ttjd dd Dd7}d}|rtjtjB_|d|tjd| dk rt| nd7}n4d_|d|tjd| dk rt| nd7}dtjd|dtjg_z(tjj_j_jj_Wn(tjk rHtdjYnXdj_d_ d_!dS)Nz%quote_char cannot be the empty stringz'endQuoteChar cannot be the empty stringrrkz{}(?:{})|z {}(?:{}.)z(.)rz{}(?:c 3s:|]2}dtjd|tj|dVqdS)z (?:{}(?!{}))N)rrrr)r<rirr*r+rN s z(QuotedString.__init__..r)z {}(?:[^{}{}])z{}(?:[^{}\n\r{}])z(?:z)*z$invalid pattern {!r} passed to RegexrFT)"r3r,rrrr quoteCharLenfirstQuoteCharrendQuoteCharLenrrrrrrrescCharReplacePatternrnrange MULTILINEDOTALLrrrrrrIrrrJrrr)r(rrrrrrrrrrrrrsep inner_patternr5rr+r, s            zQuotedString.__init__cCs4|j|jkr$t|jtr$d|jSd|j|jS)Nzstring enclosed in {!r}z.quoted string, starting with {} ending with {})rrrr"rrr*r*r+r s  z!QuotedString._generateDefaultNamecCs|||jkr|||pd}|s2t|||j||}|}|jr||j|j }t |t rd|kr|j r|j D]\}}| ||}qx|jrt|jd|}|jr| |j|j}||fS)Nrz\g<1>)rrrrr^rrrrrr"rws_mapr7rrrrrr)r(rrrr=r1wslitwscharr*r*r+r s(  zQuotedString.parseImpl)rkNNFTNT)T) r.r3r4r?rr`rrrlr,rrr?r*r*r5r+r sB& qrcsHeZdZdZdddeeeeedfddZd d Zdd d ZZ S) CharsNotInaToken for matching words composed of characters *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 ``min`` is 1 (a minimum value < 1 is not valid); the default values for ``max`` and ``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(delimited_list(csv_value).parse_string("dkls,lsdkjf,s12 34,@!#,213")) prints:: ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] rkrr)notChars) not_charsr_rtrurcstd|_|p||_t|j|_|dkr6td||_|dkrL||_nt |_|dkrf||_||_d|j |_ |jdk|_ d|_ dS)NFrzacannot specify a minimum length < 1; use Opt(CharsNotIn()) if zero-length char group is permittedrr)r3r,rrr notCharsSetrr~rrrJrrr)r(rr_rtrurr5r*r+r, s$     zCharsNotIn.__init__cCs:t|j}t|dkr*d|jddSd|jSdS)Nrz !W:({}...) z!W:({}))rrrr)r( not_chars_strr*r*r+r s  zCharsNotIn._generateDefaultNameTcCs|j}|||kr"t|||j||}|d7}t||jt|}||kr`|||kr`|d7}qB|||jkr~t|||j|||||fSr)rrrr_rrr~)r(rrrnotcharsr]maxlenr*r*r+r s  zCharsNotIn.parseImpl)rkrrr)Trlr*r*r5r+r s #rcsteZdZdZdddddddd d d d d ddddddddddddZd%eeeedfdd Zd d!Zd&d#d$Z Z S)'WhiteaSpecial 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 ``" \t\r\n"``. Also takes optional ``min``, ``max``, and ``exact`` arguments, as defined for the :class:`Word` class. zzzzzzzzz z z z zzzzzz z zzzz)rrrrr u u᠎u u u u u u u u u u u u​u u u  rr)wsr_rtrucszt|_jdfddjDddd_dj_|_ |dkr\|_ nt _ |dkrv|_ |_ dS)Nrkc3s|]}|jkr|VqdSr&) matchWhiteryrr*r+r! s z!White.__init__..Trrr) r3r,rrrn whiteStrsrrJrr~rr)r(rr_rtrur5rr+r, s  zWhite.__init__cCsddd|jDS)Nrkcss|]}tj|VqdSr&)rrryr*r*r+r4 sz-White._generateDefaultName..)rnrrr*r*r+r3 szWhite._generateDefaultNameTcCs|||jkrt|||j||}|d7}||j}t|t|}||krb|||jkrb|d7}qB|||jkrt|||j|||||fSr)rrrrr_rr~)r(rrrr]rfr*r*r+r6 s  zWhite.parseImpl)rrrr)T) r.r3r4r?rr`rr,rrr?r*r*r5r+r s8 rcseZdZfddZZS) PositionTokencstd|_d|_dSr rBrr5r*r+r,G s zPositionToken.__init__)r.r3r4r,r?r*r*r5r+rF srcs8eZdZdZedfdd ZddZd dd ZZS) GoToColumnzaToken to advance to a specific column of input text; useful for tabular report scraping. )colnocst||_dSr&)r3r,r)r(rr5r*r+r,R s zGoToColumn.__init__cCs\t|||jkrXt|}|jr*|||}||krX||rXt|||jkrX|d7}q*|Sr)rrrrisspace)r(rrrr*r*r+rV s   zGoToColumn.preParseTcCsDt||}||jkr"t||d|||j|}|||}||fS)NzText not in expected column)rr)r(rrrthiscolnewlocr1r*r*r+rc s    zGoToColumn.parseImpl)T) r.r3r4r?rr,rrr?r*r*r5r+rM s rcs2eZdZdZfddZddZd ddZZS) LineStartaMatches 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).search_string(test): print(t) prints:: ['AAA', ' this line'] ['AAA', ' and this line'] csFt|t|jB|_|jdt|j|_ d|_ dS)NrzExpected start of line) r3r,rrrorig_whiteCharsdiscardrTrr>rrr5r*r+r, s   zLineStart.__init__cCsT|dkr |S|j||}d|jkrL|||ddkrL|j||d}q$|SdS)Nrrr)r>rr)r(rrr1r*r*r+r s zLineStart.preParseTcCs*t||dkr|gfSt|||j|dSr)rrrrr*r*r+r szLineStart.parseImpl)T)r.r3r4r?r,rrr?r*r*r5r+rl s  rcs*eZdZdZfddZdddZZS)LineEndzTMatches if current position is at the end of a line within the parse string cs0t|jd|j|jddd|_dS)NrFrzExpected end of line)r3r,rrrrrr5r*r+r, s  zLineEnd.__init__TcCsb|t|kr6||dkr$|ddfSt|||j|n(|t|krN|dgfSt|||j|dS)Nrrrrrrr*r*r+r s     zLineEnd.parseImpl)TrDr*r*r5r+r s rcs*eZdZdZfddZdddZZS) StringStartzLMatches if current position is at the beginning of the parse string cstd|_dS)NzExpected start of textr3r,rrr5r*r+r, s zStringStart.__init__TcCs0|dkr(|||dkr(t|||j||gfSr)rrrrr*r*r+r szStringStart.parseImpl)TrDr*r*r5r+r s rcs*eZdZdZfddZdddZZS)rUzG Matches if current position is at the end of the parse string cstd|_dS)NzExpected end of textrrr5r*r+r, s zStringEnd.__init__TcCs^|t|krt|||j|n<|t|kr6|dgfS|t|krJ|gfSt|||j|dSrrrr*r*r+r s    zStringEnd.parseImpl)TrDr*r*r5r+rU s rUcs<eZdZdZefedeedfddZd ddZZS) WordStartaMatches if the current position is at the beginning of a :class:`Word`, and is not preceded by any character in a given set of ``word_chars`` (default= ``printables``). To emulate the ```` behavior of regular expressions, use ``WordStart(alphanums)``. ``WordStart`` will also match at the beginning of the string being parsed, or at the beginning of a line.  wordChars word_charsrcs.|tkr |n|}tt||_d|_dS)NzNot at the start of a word) printablesr3r,rrrr(rrr5r*r+r, s  zWordStart.__init__TcCs@|dkr8||d|jks(|||jkr8t|||j||gfSNrr)rrrrr*r*r+r s zWordStart.parseImpl)T r.r3r4r?rr`r,rr?r*r*r5r+r s rcs<eZdZdZefedeedfddZd ddZZS) WordEndaiMatches if the current position is at the end of a :class:`Word`, and is not followed by any character in a given set of ``word_chars`` (default= ``printables``). To emulate the ```` behavior of regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` will also match at the end of the string being parsed, or at the end of a line. rrcs4|tkr |n|}tt||_d|_d|_dS)NFzNot at the end of a word)rr3r,rrrrrr5r*r+r, s   zWordEnd.__init__TcCsPt|}|dkrH||krH|||jks8||d|jkrHt|||j||gfSr)rrrr)r(rrrrr*r*r+rs zWordEnd.parseImpl)Trr*r*r5r+r srcseZdZdZdejeedfdd Ze edddZ edd d Z deed fd d Z d eed fdd Z edfdd ZddZedfdd Zd!ddddZedfdd Zd"fdd Ze Ze ZZS)#ParseExpressionz]Abstract subclass of ParserElement, for combining and post-processing parsed tokens. Fexprsrcst|t|tr"t|}t|tr<|g_nt|trP|g_nnt|t rt|}t dd|Drfdd|D}t|_n,zt|_Wnt k r|g_YnXd_ dS)Ncss|]}t|tVqdSr&)rr")r<rr*r*r+rsz+ParseExpression.__init__..c3s&|]}t|tr|n|VqdSr&)rr"rr<r rr*r+rsF) r3r,r_generatorTyperr"rrruranyrrr(rrr5rr+r,s(        zParseExpression.__init__rKcCs|jddSr&)rrr*r*r+r+szParseExpression.recursecCs|j|d|_|Sr&)rrrr{r*r*r+r.s zParseExpression.appendTrcs<t||r8dd|jD|_|jD]}||q(|S)z Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on all contained expressions. cSsg|] }|qSr*rrr*r*r+r>;sz4ParseExpression.leave_whitespace..)r3rrr(rr r5r*r+r3s    z ParseExpression.leave_whitespacecs<t||r8dd|jD|_|jD]}||q(|S)z Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on all contained expressions. cSsg|] }|qSr*rrr*r*r+r>Gsz5ParseExpression.ignore_whitespace..)r3rrrr5r*r+r@s    z!ParseExpression.ignore_whitespacecsjt|tr>||jkrft||jD]}||jdq&n(t||jD]}||jdqP|SNr)rrrr3rr)r(r|r r5r*r+rLs      zParseExpression.ignorecCsd|jjt|jSNz{}:({}))rrr.r`rrr*r*r+rXsz$ParseExpression._generateDefaultNamecs0|jr |St|jD] }|qt|jdkr|jd}t||jr|js|jdkr|j s|jdd|jdg|_d|_ |j |j O_ |j |j O_ |jd}t||jr|js|jdkr|j s|jdd|jdd|_d|_ |j |j O_ |j |j O_ dt ||_|S)Nr\rrrr)rr3rRrrrrrrrrrrr`r)r(r r|r5r*r+rR[sD       zParseExpression.streamlineNcCsB|dk r |ngdd|g}|jD]}||q$|gdSr&)rrr)r(rtmpr r*r*r+rs  zParseExpression.validatecs t}dd|jD|_|S)NcSsg|] }|qSr*rrr*r*r+r>sz(ParseExpression.copy..)r3rrr(r1r5r*r+rs zParseExpression.copycsjtjr\tj|jkr\|jD]B}t|tr|jrtj|jkrtj d d|t |j |jddqt ||SNzY{}: setting results name {!r} on {} expression collides with {!r} on contained expressionrRr# stacklevel)rFrRr[rrrrurwarningsrHrrr.r3rr(rJrr r5r*r+rs2  zParseExpression._setResultsName)F)T)T)N)F)r.r3r4r?rrrurlr,r rrrrrrrRrrrr1r2r?r*r*r5r+r s   )rcsteZdZdZGdddeZdejee dfdd Z edfd d Z dd d Z d dZ ddZddZZS)rza Requires all given :class:`ParseExpression` s to be found in the given order. Expressions may be separated by whitespace. May be constructed using the ``'+'`` operator. May also be constructed using the ``'-'`` operator, which will suppress backtracking. Example:: integer = Word(nums) name_expr = Word(alphas)[1, ...] expr = And([integer("id"), name_expr("name"), integer("age")]) # more easily written as: expr = integer("id") + name_expr("name") + integer("age") cs$eZdZfddZddZZS)zAnd._ErrorStopcstj|||dSr&)r3r,r)r(rrr5r*r+r,szAnd._ErrorStop.__init__cCsdS)N-r*rr*r*r+rsz#And._ErrorStop._generateDefaultName)r.r3r4r,rr?r*r*r5r+rs rT) exprs_argrcst|}|rt|krg}t|D]`\}}|tkrv|t|dkrlt||djd}|t|dqtdq ||q ||dd<t |||jrt dd|jD|_ t |jdts|j|jdj|jdjd|jdj|_nd |_nd |_ d |_dS) Nrrr~z0cannot construct And with sequence ending in ...css|] }|jVqdSr&rrr*r*r+rszAnd.__init__..rrFT)rrxrdrrTrrrrr3r,rrrrrrrrr)r(rrrrrir skipto_argr5r*r+r,s2     z And.__init__rKcsH|jrtdd|jddDrt|jddD]^\}}|dkrFq4t|tr4|jr4t|jdtr4|jd|j|d|jd<d|j|d<q4dd|jD|_tt|j|jddD]f\}}t }|rt ||krq| t |t|t r| |fddq|}tt|d}qqtd d|jD|_|S) Ncss.|]&}t|to$|jo$t|jdtVqdSrN)rrrryrr*r*r+rs  z!And.streamline..rrcSsg|]}|dk r|qSr&r*rr*r*r+r>sz"And.streamline..cSst|dt||S)N parent_anchor)setattrr)r}r~rcur_r*r*r+r sz And.streamline..css|] }|jVqdSr&rrr*r*r+rs)rrrdrrryr3rRrerradd IndentedBlockrrnextrrr)r(rir prevcurseensubsr5r*r+rRs@     zAnd.streamlinec Cs|jdj|||dd\}}d}|jddD]}t|tjkrFd}q.|rz||||\}}Wqtk rvYqtk r}zd|_t|W5d}~XYqt k rt|t ||j |YqXn||||\}}|s| r.||7}q.||fS)NrFr\rT) rrrrzrParseSyntaxExceptionr5r_from_exceptionrrrhaskeys) r(rrr resultlist errorStopr  exprtokensr;r*r*r+rs<     z And.parseImplcCst|tr||}||Sr&rr"rrr{r*r*r+__iadd__3s  z And.__iadd__cCs6|dd|g}|jD]}|||jsq2qdSr&)rrrrr*r*r+r8s   zAnd._checkRecursioncCsVddd|jD}t|dkrJ|ddt|ddkrJ|dd}qd|d S) Nrcss|]}t|VqdSr&rlrr*r*r+r@sz+And._generateDefaultName..rr{}r{})rnrrr(innerr*r*r+r?s&zAnd._generateDefaultName)T)T)r.r3r4r?rTrrrrurlr,rRrrrrr?r*r*r5r+rzs !- rzcsjeZdZdZdejeedfdd Zedfdd Z dd d Z d d Z ddZ dfdd Z ZS)raRequires that at least one :class:`ParseExpression` is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the ``'^'`` operator. Example:: # construct Or using '^' operator number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) print(number.search_string("123 3.1416 789")) prints:: [['123'], ['3.1416'], ['789']] FrcsLt|||jrBtdd|jD|_tdd|jD|_nd|_dS)Ncss|] }|jVqdSr&rrr*r*r+r\szOr.__init__..css|] }|jVqdSr&rrr*r*r+r]sTr3r,rrrrrrr5r*r+r,Ys z Or.__init__rKcs^t|jrTtdd|jD|_tdd|jD|_tdd|jD|_nd|_|S)Ncss|] }|jVqdSr&rrr*r*r+rdsz Or.streamline..css|] }|jVqdSr&rrr*r*r+rescss |]}|jot|t VqdSr&rrrrr*r*r+rfsF)r3rRrrrrrrrr5r*r+rRas  z Or.streamlineTc Csd}d}g}g}tdd|jDr0|||}|jD]}z|j||dd} Wntk r} z"d| _|| _|| d}d}W5d} ~ XYq6tk r} z"|sd| _| j |kr| }| j }W5d} ~ XYq6t k r t ||krt|t ||j |}t |}Yq6X|| |fq6|r|j tddd|sT|dd} | |||Sd } |D]\}}|| dkrz| Sz||||\} }Wn@tk r} z d| _| j |kr| }| j }W5d} ~ XYn.X| |kr| |fS| | dkr\| |f} q\| d kr| S|rft |dkrZ|j d d d |dj |dj krZ|j d d d |d}||dk r~|j |_|nt||d|dS)Nrcss|] }|jVqdSr&)rrr*r*r+rrszOr.parseImpl..Tr+r)rreverserrcSs|j Sr&rr r*r*r+rrzOr.parseImpl..rcSs|j tt|j fSr&rrr` parserElementr$r*r*r+rr no defined alternatives to match)rrrr-rrr'rrrrrrsortrrr)r(rrr maxExcLoc maxExceptionrdfatalsr loc2pfer' best_exprlongestloc1expr1r max_fatalr*r*r+rms            z Or.parseImplcCst|tr||}||Sr&rr{r*r*r+__ixor__s  z Or.__ixor__cCsdddd|jDdS)Nrz ^ css|]}t|VqdSr&rlrr*r*r+rsz*Or._generateDefaultName..rrnrrr*r*r+rszOr._generateDefaultNamecsRtjrDtj|jkrDtdd|jDrDtjdd|t |j ddt ||S)Ncss$|]}t|totj|jkVqdSr&rrzr[rQrrr*r*r+rs  z%Or._setResultsName..{}: setting results name {!r} on {} expression will return a list of all parsed tokens in an And alternative, in prior versions only the first token was returned; enclose contained argument in GrouprQr#r rFrQr[rrrrrHrrr.r3rr(rJrr5r*r+rs$ zOr._setResultsName)F)T)F)r.r3r4r?rrrurlr,rRrr4rrr?r*r*r5r+rGs RrcsjeZdZdZdejeedfdd Zedfdd Z dd d Z d d Z ddZ dfdd Z ZS)raRequires that at least one :class:`ParseExpression` is found. If more than one expression matches, the first one listed is the one that will match. May be constructed using the ``'|'`` operator. Example:: # construct MatchFirst using '|' operator # watch the order of expressions to match number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) print(number.search_string("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] # put more selective expression first number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) print(number.search_string("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] FrcsLt|||jrBtdd|jD|_tdd|jD|_nd|_dS)Ncss|] }|jVqdSr&rrr*r*r+rsz&MatchFirst.__init__..css|] }|jVqdSr&rrr*r*r+rsTrrr5r*r+r,s zMatchFirst.__init__rKcsn|jr |St|jr^tdd|jD|_tdd|jD|_tdd|jD|_n d|_d|_|S)Ncss|] }|jVqdSr&rrr*r*r+rsz(MatchFirst.streamline..css|] }|jVqdSr&rrr*r*r+rscss |]}|jot|t VqdSr&r rr*r*r+rsFT) rr3rRrrrrrrrr5r*r+rRs  zMatchFirst.streamlineTc Csd}d}|jD]}z||||WStk rV}zd|_||_W5d}~XYqtk r}z|j|krz|}|j}W5d}~XYqtk rt||krt|t||j |}t|}YqXq|dk r|j |_ |nt||d|dS)Nrr() rrrrr'rrrrrr) r(rrrr*r+r r.r'r*r*r+r sF    zMatchFirst.parseImplcCst|tr||}||Sr&rr{r*r*r+__ior__.s  zMatchFirst.__ior__cCsdddd|jDdS)Nrz | css|]}t|VqdSr&rlrr*r*r+r4sz2MatchFirst._generateDefaultName..rr5rr*r*r+r3szMatchFirst._generateDefaultNamecsRtjrDtj|jkrDtdd|jDrDtjdd|t |j ddt ||S)Ncss$|]}t|totj|jkVqdSr&r6rr*r*r+r<s  z-MatchFirst._setResultsName..r7rQr#rr8r9r5r*r+r6s$ zMatchFirst._setResultsName)F)T)F)r.r3r4r?rrrurlr,rRrr:rrr?r*r*r5r+rs "rcsTeZdZdZd ejeedfdd Zedfdd Z dd d Z d d Z Z S)ralRequires all given :class:`ParseExpression` s to be found, but in any order. Expressions may be separated by whitespace. May be constructed using the ``'&'`` operator. Example:: color = one_of("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") shape_type = one_of("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 & Opt(color_attr) & Opt(size_attr) shape_spec.run_tests(''' 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 TrcsHt|||jr,tdd|jD|_nd|_d|_d|_d|_dS)Ncss|] }|jVqdSr&rrr*r*r+rsz Each.__init__..T)r3r,rrrrinitExprGroupsrrr5r*r+r,sz Each.__init__rKcs2t|jr(tdd|jD|_nd|_|S)Ncss|] }|jVqdSr&rrr*r*r+rsz"Each.streamline..T)r3rRrrrrr5r*r+rRs  zEach.streamlinec s|jrtdd|jD|_dd|jD}dd|jD}|||_dd|jD|_dd|jD|_dd|jD|_|j|j7_d |_|}|jdd}|jdd|jdd}g} d } g} g} | r||} | | | D]}z|j ||d d }Wnbt k rR}z$d|_ ||_ | || |W5d}~XYqtk rp| |YqX| |jt||||kr||q|kr|qt| t| krd } q| r t| d kr| jd dd| dj| d jkr| jddd| d}||rLddd|D}t||d|| fdd|jD7} tg}| D] }||||\}}||7}qp||fS)Ncss&|]}t|trt|j|fVqdSr&)rrrrrr*r*r+rs z!Each.parseImpl..cSsg|]}t|tr|jqSr*rrrrr*r*r+r>s z"Each.parseImpl..cSs&g|]}|jrt|tttfs|qSr*)rrrrrrr*r*r+r>scSs(g|] }t|tr|jj|jddqST)r)r_MultipleMatchrrrrr*r*r+r>s cSs(g|] }t|tr|jj|jddqSr=)rrrrrrr*r*r+r>s cSs g|]}t|tttfs|qSr*)rrrrrr*r*r+r>sFTr!rcSs|j Sr&r#r$r*r*r+rrz Each.parseImpl..r%rcSs|j tt|j fSr&r&r$r*r*r+rrz, cSsg|] }t|qSr*rlrr*r*r+r>sz*Missing one or more required elements ({})cs$g|]}t|tr|jkr|qSr*r<rtmpOptr*r+r>s )r;dictropt1map optionalsmultioptionals multirequiredrequiredr?r-rrr'rrrrremoverr)rrnrrr)r(rrropt1opt2tmpLoctmpReqdmultis matchOrder keepMatchingfailedr,tmpExprsr r.r3missing total_resultsrkr*r?r+rs        zEach.parseImplcCsdddd|jDdS)Nrz & css|]}t|VqdSr&rlrr*r*r+rsz,Each._generateDefaultName..rr5rr*r*r+rszEach._generateDefaultName)T)T) r.r3r4r?rrrurlr,rRrrr?r*r*r5r+rQs 9  WrcseZdZdZdeeefedfdd Ze edddZ dd d Z deed fd d Z deed fdd Z edfdd Zedfdd ZddZd ddddZddZe Ze ZZS)!ParseElementEnhancezfAbstract subclass of :class:`ParserElement`, for combining and post-processing parsed tokens. Frrcst|t|trVt|jtr.||}n(tt||jrHt|}n|t|}||_ |dk r|j |_ |j |_ |j |j |jd|j|_|j|_|j|_|j|jdS)Nr)r3r,rr" issubclassrr@rrrrrrrrrrrrrmr(rrr5r*r+r,s&     zParseElementEnhance.__init__rKcCs|jdk r|jgSgSr&rrr*r*r+rszParseElementEnhance.recurseTcCs0|jdk r|jj|||ddSt||d|dS)NFr\zNo expression defined)rrrrr*r*r+rs zParseElementEnhance.parseImplrcs6t||r2|j|_|jdk r2|j||Sr&)r3rrrrr5r*r+rs     z$ParseElementEnhance.leave_whitespacecs6t||r2|j|_|jdk r2|j||Sr&)r3rrrrr5r*r+r$s     z%ParseElementEnhance.ignore_whitespacecsjt|tr>||jkrft||jdk rf|j|jdn(t||jdk rf|j|jd|Sr)rrrr3rrr{r5r*r+r-s      zParseElementEnhance.ignorecs"t|jdk r|j|Sr&)r3rRrrr5r*r+rR9s   zParseElementEnhance.streamlinecCsB||krt||g|dd|g}|jdk r>|j|dSr&)RecursiveGrammarExceptionrr)r(rrr*r*r+r?s  z#ParseElementEnhance._checkRecursionNcCsB|dkr g}|dd|g}|jdk r4|j||gdSr&rrrr(rrr*r*r+rFs   zParseElementEnhance.validatecCsd|jjt|jSr)rrr.r`rrr*r*r+rNsz(ParseElementEnhance._generateDefaultName)F)T)T)T)N)r.r3r4r?rrur`rlr,r rrrrrrRrrrr1r2r?r*r*r5r+rSs    rScs\eZdZdZGdddeZGdddeZdddeeed fd d Z dd d Z Z S)r z Expression to match one or more expressions at a given indentation level. Useful for parsing text where structure is implied by indentation (like Python source code). cs"eZdZedfdd ZZS)zIndentedBlock._Indentref_colcs,td|_|fdddS)Nzexpected indent at column {}cst||kSr&rr|r[r*r+r_rz0IndentedBlock._Indent.__init__..r3r,rrrr(r\r5r[r+r,\s  zIndentedBlock._Indent.__init__r.r3r4rr,r?r*r*r5r+_Indent[sracs"eZdZedfdd ZZS)zIndentedBlock._IndentGreaterr[cs,td|_|fdddS)Nz)expected indent at column greater than {}cst||kSr&r]r|r[r*r+rerz7IndentedBlock._IndentGreater.__init__..r^r_r5r[r+r,bs  z%IndentedBlock._IndentGreater.__init__r`r*r*r5r+_IndentGreaterasrbFTrgrouped)rrrdcs&tj|dd||_||_d|_dS)NTrr)r3r, _recursive_groupedr)r(rrrdr5r*r+r,gszIndentedBlock.__init__c Cst||}|j|||t||}||}t||j}|jr||}t|j|j|j d} | |j || _ |t || 7}|dtt|ddd|t|} ||j tB} |j rt} ndd} | | t| |||S)Nrczinner @cSs|Sr&r*rWr*r*r+rrz)IndentedBlock.parseImpl..)rTrrr-rrarerbr rfrrrrrhexrrVrrUGrouprr) r(rrr anchor_loc indent_colpeer_detect_expr inner_expr sub_indent nested_blockblocktrailing_undentrr*r*r+rqs4    *zIndentedBlock.parseImpl)T) r.r3r4r?rTrarbrurlr,rr?r*r*r5r+r Us r cs<eZdZdZeeefdfdd Zdfdd ZZ S) AtStringStartzMatches if expression matches at the beginning of the parse string:: AtStringStart(Word(nums)).parse_string("123") # prints ["123"] AtStringStart(Word(nums)).parse_string(" 123") # raises ParseException rWcst|d|_dSNFr3r,rr(rr5r*r+r,s zAtStringStart.__init__Tcs$|dkrt||dt|||S)Nrznot found at string start)rr3rrr5r*r+rs zAtStringStart.parseImpl)T r.r3r4r?rrur`r,rr?r*r*r5r+rss rscs<eZdZdZeeefdfdd Zdfdd ZZ S) AtLineStartaMatches if an expression matches 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 (AtLineStart('AAA') + restOfLine).search_string(test): print(t) prints:: ['AAA', ' this line'] ['AAA', ' and this line'] rWcst|d|_dSrtrurvr5r*r+r,s zAtLineStart.__init__Tcs*t||dkrt||dt|||S)Nrznot found at line start)rrr3rrr5r*r+rs zAtLineStart.parseImpl)Trwr*r*r5r+rxsrxcs8eZdZdZeeefdfdd ZdddZZ S) FollowedByacLookahead matching of the given parse expression. ``FollowedBy`` does *not* advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current position. ``FollowedBy`` always returns a null token list. If any results names are defined in the lookahead expression, those *will* be returned for access by name. 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, stop_on=label).set_parse_action(' '.join)) attr_expr[1, ...].parse_string("shape: SQUARE color: BLACK posn: upper left").pprint() prints:: [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] rWcst|d|_dSrr3r,rrvr5r*r+r,s zFollowedBy.__init__TcCs(|jj|||d\}}|dd=||fS)Nr,)rr)r(rrrr8r1r*r*r+rs zFollowedBy.parseImpl)Trwr*r*r5r+rysrycsBeZdZdZd eeefeje dfdd Z d dd Z Z S) PrecededByaLookbehind matching of the given parse expression. ``PrecededBy`` does not advance the parsing position within the input string, it only verifies that the specified parse expression matches prior to the current position. ``PrecededBy`` always returns a null token list, but if a results name is defined on the given expression, it is returned. Parameters: - expr - expression that must match prior to the current parse location - retreat - (default= ``None``) - (int) maximum number of characters to lookbehind prior to the current parse location If the lookbehind expression is a string, :class:`Literal`, :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn` with a specified exact or maximum length, then the retreat parameter is not required. Otherwise, retreat must be specified to give a maximum number of characters to look back from the current parse position for a lookbehind match. Example:: # VB-style variable names with type prefixes int_var = PrecededBy("#") + pyparsing_common.identifier str_var = PrecededBy("$") + pyparsing_common.identifier N)rretreatcst|||_d|_d|_d|_t|trFt |}d|_nVt|t t frb|j }d|_n:t|t tfr|jtkr|j}d|_nt|trd}d|_||_dt||_d|_|jdddS)NTFrznot preceded by cSs|tddSr&) __delitem__slicer|r*r*r+r$rz%PrecededBy.__init__..)r3r,rrrrrurr"rrrPrJrmrrrrr|r`rrrr)r(rr|r5r*r+r, s*   zPrecededBy.__init__rTc Cs|jr<||jkrt|||j||j}|j||\}}n|jt}|td||j|}t|||j} tdt ||jddD]L} z||t || \}}Wn&t k r} z| } W5d} ~ XYqXqq| ||fSr) rur|rrrrrUrtrr_rr5) r(rrrr]r8r1 test_exprinstring_slice last_exproffsetpber*r*r+r&s&    zPrecededBy.parseImpl)N)rT) r.r3r4r?rrur`rrrr,rr?r*r*r5r+r{s r{c@seZdZdZdddZdS)Locateda Decorates 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 ```` characters, you may want to call :class:`ParserElement.parse_with_tabs` Example:: wd = Word(alphas) for match in Located(wd).search_string("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [0, ['ljsdf'], 5] [8, ['lksdjjf'], 15] [18, ['lkkjj'], 23] TcCs^|}|jj|||dd\}}t|||g}||d<||d<||d<|jrR||gfS||fSdS)NFr\ locn_startr:locn_end)rrrr)r(rrrr]r&r(r*r*r+r\s zLocated.parseImplN)T)r.r3r4r?rr*r*r*r+r@srcs@eZdZdZeeefdfdd Zd ddZdd Z Z S) ra Lookahead to disallow matching with the given parse expression. ``NotAny`` does *not* advance the parsing position within the input string, it only verifies that the specified parse expression does *not* match at the current position. Also, ``NotAny`` does *not* skip over leading whitespace. ``NotAny`` always returns a null token list. May be constructed using the ``'~'`` operator. Example:: AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split()) # take care not to mistake keywords for identifiers ident = ~(AND | OR | NOT) + Word(alphas) boolean_term = Opt(NOT) + ident # very crude boolean expression - to support parenthesis groups and # operation hierarchy, use infix_notation boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...] # integers that are followed by "." are actually floats integer = Word(nums) + ~Char(".") rWcs,t|d|_d|_dt|j|_dS)NFTzFound unwanted token, )r3r,rrr`rrrvr5r*r+r,s zNotAny.__init__TcCs&|j||rt|||j||gfSr&)rr.rrrr*r*r+rszNotAny.parseImplcCsdt|jdS)Nz~{rr`rrr*r*r+rszNotAny._generateDefaultName)T) r.r3r4r?rrur`r,rrr?r*r*r5r+rjs rcspeZdZdddeejeeefejeeefdfddZedddZ dd d Z dfd d Z Z S)r>NstopOnrstop_onrcs@t||p|}d|_|}t|tr2||}||dSr)r3r,rrr"rr)r(rrrenderr5r*r+r,s   z_MultipleMatch.__init__rKcCs,t|tr||}|dk r"|nd|_|Sr&)rr"r not_ender)r(rr*r*r+rs  z_MultipleMatch.stopOnTc Cs|jj}|j}|jdk }|r$|jj}|r2|||||||\}}zV|j } |r\|||| rl|||} n|} ||| |\}} | s| rN|| 7}qNWnttfk rYnX||fSr&) rrrrr!rrrr) r(rrrself_expr_parseself_skip_ignorables check_ender try_not_enderr&hasIgnoreExprsre tmptokensr*r*r+rs*      z_MultipleMatch.parseImplFcsvtjrhtj|jkrh|jg|jD]B}t|tr$|jr$tj|jkr$t j d d|t |j |jddq$t||Sr)rFrRr[rrrrrurrrHrrr.r3rrr5r*r+rs2 z_MultipleMatch._setResultsName)N)T)F) r.r3r4rurrrr`r,rrrr?r*r*r5r+r>s r>c@seZdZdZddZdS)rar Repetition of one or more of the given expression. Parameters: - expr - expression that must match one or more times - stop_on - (default= ``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).set_parse_action(' '.join)) text = "shape: SQUARE posn: upper left color: BLACK" attr_expr[1, ...].parse_string(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] # use stop_on attribute for OneOrMore to avoid reading label string as part of the data attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) OneOrMore(attr_expr).parse_string(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] # could also be written as (attr_expr * (1,)).parse_string(text).pprint() cCsdt|jdS)Nrz}...rrr*r*r+rszOneOrMore._generateDefaultNameN)r.r3r4r?rr*r*r*r+rsrcsdeZdZdZd ddeejeeefejeeefdfddZ d fdd Z d d Z Z S)rao Optional repetition of zero or more of the given expression. Parameters: - ``expr`` - expression that must match zero or more times - ``stop_on`` - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) - (default= ``None``) Example: similar to :class:`OneOrMore` Nrrcstj||p|dd|_dS)NrTrz)r(rrrr5r*r+r,szZeroOrMore.__init__Tc sBzt|||WSttfk r<|tg|jdfYSXdS)Nr)r3rrrrrrr5r*r+rszZeroOrMore.parseImplcCsdt|jdS)N[z]...rrr*r*r+rszZeroOrMore._generateDefaultName)N)T) r.r3r4r?rurrrr`r,rrr?r*r*r5r+rs rc@seZdZddZddZdS) _NullTokencCsdSrtr*rr*r*r+__bool__$sz_NullToken.__bool__cCsdSrr*rr*r*r+r'sz_NullToken.__str__N)r.r3r4rrr*r*r*r+r#srcsLeZdZdZeZefeeefe dfdd Z d ddZ dd Z Z S) raN 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) + Opt('-' + Word(nums, exact=4))) zip.run_tests(''' # 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) )rdefaultcs*tj|dd|jj|_||_d|_dS)NFrT)r3r,rr defaultValuer)r(rrr5r*r+r,Ts z Opt.__init__Tc Csz|j}z|j|||dd\}}WnPttfk rp|j}||jk rh|jr`t|g}|||j<ql|g}ng}YnX||fS)NFr\)rrrrr_Opt__optionalNotMatchedrr)r(rrr self_exprr& default_valuer*r*r+r\s    z Opt.parseImplcCsJt|j}t|dkr>|ddt|ddkr>|dd}q d|dS)Nrrrrr])r`rrrr*r*r+rls &zOpt._generateDefaultName)T)r.r3r4r?rrrrur`rr,rrr?r*r*r5r+r+s&  rc s^eZdZdZd ddeeefeeej eeefeeefdfddZ d d d Z Z S) ra* 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`` - if ``True``, the target expression is also parsed (the skipped text and target expression are returned as a 2-element list) (default= ``False``). - ``ignore`` - (default= ``None``) used to define grammars (typically quoted strings and comments) that might contain false matches to the target expression - ``fail_on`` - (default= ``None``) define expressions that are not allowed to be included in the skipped test; if found before the target expression is found, the :class:`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=quoted_string) string_data.set_parse_action(token_map(str.strip)) ticket_expr = (integer("issue_num") + SEP + string_data("sev") + SEP + string_data("desc") + SEP + integer("days_open")) for tkt in ticket_expr.search_string(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' FN)failOn)r|includerfail_onrcsdt||p|}||_d|_d|_||_d|_t|trJ| ||_ n||_ dt |j |_ dS)NTFzNo match found for )r3r, ignoreExprrr includeMatchrrr"rrr`rr)r(r|rrrrr5r*r+r,s  zSkipTo.__init__Tc Cs |}t|}|jj}|jdk r&|jjnd}|jdk r<|jjnd}|} | |kr|dk r`||| r`q|dk rz||| } Wqhtk rYqYqhXqhz||| dddWqtt fk r| d7} YqDXqqDt|||j || }|||} t | } |j r||||dd\}} | | 7} || fS)NF)rrrr\) rrrrr"rr!r5rrrrr) r(rrrrrrself_failOn_canParseNextself_ignoreExpr_tryParsetmplocskiptext skipresultrjr*r*r+rs<   zSkipTo.parseImpl)FNN)T) r.r3r4r?rrur`rlrrr,rr?r*r*r5r+rws?  rcseZdZdZd"ejeeefdfdd Z ddZ dd Z fd d Z d d Z d#fdd Zd$eedddZd%eedddZedddZd&ddddZddZedfdd Zd'fd d! ZeZeZZS)(r/aw 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 ``Forward`` variable using the ``'<<'`` operator. Note: take care when assigning to ``Forward`` not to overlook precedence of operators. Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that:: fwd_expr << a | b | c will actually be evaluated as:: (fwd_expr << a) | b | c thereby leaving b and c out as parseable alternatives. It is recommended that you explicitly group the values inserted into the ``Forward``:: fwd_expr << (a | b | c) Converting to use the ``'<<='`` operator instead will avoid this problem. See :class:`ParseResults.pprint` for an example of a recursive parser created using ``Forward``. N)r|cs,tjddd|_tj|ddd|_dS)Nr\rrFr)rr caller_framer3r, lshift_liner{r5r*r+r,szForward.__init__cCst|dr|`t|tr"||}||_|jj|_|jj|_|j|jj |jj d|jj |_ |jj |_ |j |jj tjddd|_|S)Nrrr\r)rrrr"rrrrrrrrrrrmrrrr{r*r*r+ __lshift__s        zForward.__lshift__cCs||>Sr&r*r{r*r*r+ __ilshift__0szForward.__ilshift__csJtjddd}tjr:||jkr:tj|jkr:tjdddt |}|S)Nr\rrz}z||f| | <| | <W5d}~XYnX||f\} }| | <q0YnXW5QRXdS)NrXrhrrrqrr)r]r\zGForward expression was never assigned a value, will not parse any inputrTFz#Forward recursion without base case)rrFrTr[rrrrdreversedrJrrHrurAr3rrr0rrrKeyErrorr)r(rrr parse_fnsrrifrmrmemoprev_loc prev_resultact_keypeek_key prev_peeknew_locnew_peekr r5r*r+rPs          zForward.parseImplrcCs d|_|Srtrrr*r*r+rszForward.leave_whitespacecCs d|_|Srrrr*r*r+rszForward.ignore_whitespacerKcCs$|js d|_|jdk r |j|Sr)rrrRrr*r*r+rRs   zForward.streamlinecCsJ|dkr g}||kr<|dd|g}|jdk r<|j||gdSr&rYrZr*r*r+rs  zForward.validatec CsNd|_d}dz&|jdk r,t|jdd}nd}W5|jjd|SX)Nz: ...r6z: iNone)rrr.rr`)r( retStringr*r*r+rs zForward._generateDefaultNamecs*|jdk rtSt}||K}|SdSr&)rr3rr/rr5r*r+rs   z Forward.copyFcsHtjr:tj|jkr:|jdkr:tjdd|t|j ddt ||S)NzO{}: setting results name {!r} on {} expression that has no contained expressionrSr#r) rFrSr[rrrrHrrr.r3r)r(rJrr5r*r+rs  zForward._setResultsName)N)T)T)T)N)F)r.r3r4r?rrrrur`r,rrrrrrlrrrRrrrrr1r2r?r*r*r5r+r/s " _ r/cs0eZdZdZdeeefdfdd ZZS)TokenConverterzW Abstract subclass of :class:`ParseExpression`, for converting parsed results. FrWcst|d|_dSrt)r3r,rrVr5r*r+r,s zTokenConverter.__init__)F) r.r3r4r?rrur`r,r?r*r*r5r+rsrcsTeZdZdZdddeeeejedfddZ ed fd d Z d d Z Z S)CombineaConverter 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 ``'adjacent=False'`` in the constructor. Example:: real = Word(nums) + '.' + Word(nums) print(real.parse_string('3.1416')) # -> ['3', '.', '1416'] # will also erroneously match the following print(real.parse_string('3. 1416')) # -> ['3', '.', '1416'] real = Combine(Word(nums) + '.' + Word(nums)) print(real.parse_string('3.1416')) # -> ['3.1416'] # no match when there are internal spaces print(real.parse_string('3. 1416')) # -> Exception: Expected W:(0123...) rkTN) joinString)r join_stringadjacentrcsDt||dk r|n|}|r(|||_d|_||_d|_dSr)r3r,rrrrr)r(rrrrr5r*r+r,s zCombine.__init__rKcs$|jrt||n t||Sr&)rrurr3r{r5r*r+r"s zCombine.ignorecCsP|}|dd=|td||jg|jd7}|jrH|rH|gS|SdS)Nrk)r)rrrn _asStringListrrrr)r(rrrretToksr*r*r+r)s zCombine.postParse)rkT) r.r3r4r?rur`rlrrr,rrr?r*r*r5r+rsrcs2eZdZdZdeedfdd ZddZZS) rjaConverter to return the matched tokens as a list - useful for returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions. The optional ``aslist`` argument when set to True will return the parsed tokens as a Python list instead of a pyparsing ParseResults. Example:: ident = Word(alphas) num = Word(nums) term = ident | num func = ident + Opt(delimited_list(term)) print(func.parse_string("fn a, b, 100")) # -> ['fn', 'a', 'b', '100'] func = ident + Group(Opt(delimited_list(term))) print(func.parse_string("fn a, b, 100")) # -> ['fn', ['a', 'b', '100']] F)raslistcst|d|_||_dSr)r3r,r _asPythonList)r(rrr5r*r+r,Ks zGroup.__init__cCs0|jr&tt|tr|nt|S|gSdSr&)rrrrrrrr*r*r+rPs zGroup.postParse)F r.r3r4r?rurlr,rr?r*r*r5r+rj6srjcs2eZdZdZdeedfdd ZddZZS) rarConverter 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. The optional ``asdict`` argument when set to True will return the parsed tokens as a Python dict instead of a pyparsing ParseResults. Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) # print attributes as plain groups print(attr_expr[1, ...].parse_string(text).dump()) # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) - Dict will auto-assign names result = Dict(Group(attr_expr)[1, ...]).parse_string(text) print(result.dump()) # access named fields as dict entries, or output as dict print(result['shape']) print(result.as_dict()) 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 :class:`ParseResults` of accessing fields by results name. F)rasdictcst|d|_||_dSr)r3r,r _asPythonDict)r(rrr5r*r+r,s z Dict.__init__c Cs6t|D]\}}t|dkrq|d}t|tr> entering method-name(line:, , )"``. When the parse action completes, the decorator will print ``"<<"`` followed by the returned value, or any exception that the parse action raised. Example:: wd = Word(alphas) @trace_parse_action def remove_duplicate_chars(tokens): return ''.join(sorted(set(''.join(tokens)))) wds = wd[1, ...].set_parse_action(remove_duplicate_chars) print(wds.parse_string("slkdjs sld sldd sdlf sdljf")) prints:: >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) <>entering {}(line: {!r}, {}, {!r}) z<.z)rr.)rrr*rr+trace_parse_actions rempty line_startline_end string_start string_endz\[]-*.$+^?()~ r\)rucCs |ddSrr*r|r*r*r+r rrz\\0?[xX][0-9a-fA-F]+cCstt|dddS)Nrz\0xr)chrrrr|r*r*r+r#rz \\0[0-7]+cCstt|ddddS)Nrrr$)rrr|r*r*r+r&rz\]rr^negatebodyr)r}rLcsFddz"dfddt|jDWStk r@YdSXdS)a Helper to easily define string ranges for use in :class:`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 ``\-`` or ``\]``) - an escaped hex character with a leading ``'\x'`` (``\x21``, which is a ``'!'`` character) (``\0x##`` is also supported for backwards compatibility) - an escaped octal character with a leading ``'\0'`` (``\041``, which is a ``'!'`` character) - a range of any of the above, separated by a dash (``'a-z'``, etc.) - any combination of the above (``'aeiouy'``, ``'a-zA-Z0-9_$'``, etc.) cSs<t|ts|Sdddtt|dt|ddDS)Nrkcss|]}t|VqdSr&)rryr*r*r+rQsz+srange....rr)rrrnrord)pr*r*r+rOszsrange..rkc3s|]}|VqdSr&r*)r<part _expandedr*r+rTszsrange..N)rn_reBracketExprrXrr)r}r*rr+srange4s "rcs,fdd}tdtdj}||_|S)a^Helper to define a parse action by mapping a function to all elements of a :class:`ParseResults` list. If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``, which will convert the parsed data to an integer using base 16. Example (compare the last to example in :class:`ParserElement.transform_string`:: hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16)) hex_ints.run_tests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).set_parse_action(token_map(str.upper)) upperword[1, ...].run_tests(''' my kingdom for a horse ''') wd = Word(alphas).set_parse_action(token_map(str.title)) wd[1, ...].set_parse_action(' '.join).run_tests(''' 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'] csfdd|DS)Ncsg|]}|fqSr*r*)r<toknrr)r*r+r>sz)token_map..pa..r*r|rr*r+r~sztoken_map..par.r)rr.)r)rrrr*rr+ token_mapYs%rcCs8tjjD]"\}}t|tr|js||qdS)zy Utility to simplify mass-naming of parser elements, for generating railroad diagram with named subdiagrams. N) r _getframef_backf_localsrrrurr)rJvarr*r*r+autoname_elementssrz4"(?:[^"\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 quotesuzunicode string literalz#[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]z[\0xa1-\0xbf\0xd7\0xf7]cCsg|]}t|tr|qSr*)rru)r<rr*r*r+r>s r)r#)NF)F)F)F)osrrrrrrrrr r r abcr r enumrrwrrrrcollections.abcrrtypesoperatorr functoolsr threadingrpathlibrutilrrrrrrrrrJrrI exceptionsactionsrkrr unicoder!maxsizerr`bytesr"rr version_infor%r5rFr[rcrerPrrlrt warnoptionsenvironrsumrrzrrrrrrr_rtr GeneratorTyperrrrrrrrrascii_uppercaseascii_lowercasealphasLatin1 identcharsidentbodycharsnumshexnumsrZrn printablerr{ StackSummaryrrrrrrruryr@rTrCrrLrrPr\r^r_rmrrrrrrrrrrrrUrrrrzrrrrSr rsrxryr{rrr>rrrrrr/rrrjrrrrrrrrrr _escapedPunc_escapedHexChar_escapedOctChar _singleChar _charRangerrrrrdbl_quoted_stringsgl_quoted_stringrunicode_string alphas8bitpunc8bitrvaluesrtokenMapconditionAsParseActionnullDebugActionsglQuotedStringdblQuotedString quotedString unicodeString lineStartlineEnd stringStart stringEndtraceParseActionr*r*r*r+s0       ,    !        =    *)  -vYq EPM/"o(]@!$Q*+N!Iw 9%W70      %.