o
    _c4                     @   sT  d Z ddlmZ dZddlZddlZddlmZmZmZm	Z	 ddl
mZ ddlmZ ddlZd ZeeZd]d	d
ZG dd dZG dd dZdd ZG dd deZed^i dddddddddddddddddd d!d"d#d"d$d%d&d%d'd(d)d(d*d+d,d+d-d.d/d.d0d1d2d1d3d4d5d4Zd6Zd7Zd8d9e Zd:Zd;Z d<Z!									d_d=d>Z"G d?d@ d@e#Z$G dAdB dBe#Z%e&dCZ'e(e)dDdEdF dGD  Z*dHdI Z+e&dJZ,G dKdL dLe-Z.G dMdN dNe-Z/G dOdP dPe-Z0G dQdR dRe-Z1d`dUdVZ2				S	TdadWdXZ3				S	TdadYdZZ4dbd[d\Z&dS )ca.H  Parse strings using a specification based on the Python format() syntax.

   ``parse()`` is the opposite of ``format()``

The module is set up to only export ``parse()``, ``search()``, ``findall()``,
and ``with_pattern()`` when ``import \*`` is used:

>>> from parse import *

From there it's a simple thing to parse a string:

.. code-block:: pycon

    >>> parse("It's {}, I love it!", "It's spam, I love it!")
    <Result ('spam',) {}>
    >>> _[0]
    'spam'

Or to search a string for some pattern:

.. code-block:: pycon

    >>> search('Age: {:d}\n', 'Name: Rufus\nAge: 42\nColor: red\n')
    <Result (42,) {}>

Or find all the occurrences of some pattern in a string:

.. code-block:: pycon

    >>> ''.join(r[0] for r in findall(">{}<", "<p>the <b>bold</b> text</p>"))
    'the bold text'

If you're going to use the same pattern to match lots of strings you can
compile it once:

.. code-block:: pycon

    >>> from parse import compile
    >>> p = compile("It's {}, I love it!")
    >>> print(p)
    <Parser "It's {}, I love it!">
    >>> p.parse("It's spam, I love it!")
    <Result ('spam',) {}>

("compile" is not exported for ``import *`` usage as it would override the
built-in ``compile()`` function)

The default behaviour is to match strings case insensitively. You may match with
case by specifying `case_sensitive=True`:

.. code-block:: pycon

    >>> parse('SPAM', 'spam', case_sensitive=True) is None
    True


Format Syntax
-------------

A basic version of the `Format String Syntax`_ is supported with anonymous
(fixed-position), named and formatted fields::

   {[field name]:[format spec]}

Field names must be a valid Python identifiers, including dotted names;
element indexes imply dictionaries (see below for example).

Numbered fields are also not supported: the result of parsing will include
the parsed fields in the order they are parsed.

The conversion of fields to types other than strings is done based on the
type in the format specification, which mirrors the ``format()`` behaviour.
There are no "!" field conversions like ``format()`` has.

Some simple parse() format string examples:

.. code-block:: pycon

    >>> parse("Bring me a {}", "Bring me a shrubbery")
    <Result ('shrubbery',) {}>
    >>> r = parse("The {} who {} {}", "The knights who say Ni!")
    >>> print(r)
    <Result ('knights', 'say', 'Ni!') {}>
    >>> print(r.fixed)
    ('knights', 'say', 'Ni!')
    >>> print(r[0])
    knights
    >>> print(r[1:])
    ('say', 'Ni!')
    >>> r = parse("Bring out the holy {item}", "Bring out the holy hand grenade")
    >>> print(r)
    <Result () {'item': 'hand grenade'}>
    >>> print(r.named)
    {'item': 'hand grenade'}
    >>> print(r['item'])
    hand grenade
    >>> 'item' in r
    True

Note that `in` only works if you have named fields.

Dotted names and indexes are possible with some limits. Only word identifiers
are supported (ie. no numeric indexes) and the application must make additional
sense of the result:

.. code-block:: pycon

    >>> r = parse("Mmm, {food.type}, I love it!", "Mmm, spam, I love it!")
    >>> print(r)
    <Result () {'food.type': 'spam'}>
    >>> print(r.named)
    {'food.type': 'spam'}
    >>> print(r['food.type'])
    spam
    >>> r = parse("My quest is {quest[name]}", "My quest is to seek the holy grail!")
    >>> print(r)
    <Result () {'quest': {'name': 'to seek the holy grail!'}}>
    >>> print(r['quest'])
    {'name': 'to seek the holy grail!'}
    >>> print(r['quest']['name'])
    to seek the holy grail!

If the text you're matching has braces in it you can match those by including
a double-brace ``{{`` or ``}}`` in your format string, just like format() does.


Format Specification
--------------------

Most often a straight format-less ``{}`` will suffice where a more complex
format specification might have been used.

Most of `format()`'s `Format Specification Mini-Language`_ is supported:

   [[fill]align][0][width][.precision][type]

The differences between `parse()` and `format()` are:

- The align operators will cause spaces (or specified fill character) to be
  stripped from the parsed value. The width is not enforced; it just indicates
  there may be whitespace or "0"s to strip.
- Numeric parsing will automatically handle a "0b", "0o" or "0x" prefix.
  That is, the "#" format character is handled automatically by d, b, o
  and x formats. For "d" any will be accepted, but for the others the correct
  prefix must be present if at all.
- Numeric sign is handled automatically.
- The thousands separator is handled automatically if the "n" type is used.
- The types supported are a slightly different mix to the format() types.  Some
  format() types come directly over: "d", "n", "%", "f", "e", "b", "o" and "x".
  In addition some regular expression character group types "D", "w", "W", "s"
  and "S" are also available.
- The "e" and "g" types are case-insensitive so there is not need for
  the "E" or "G" types. The "e" type handles Fortran formatted numbers (no
  leading 0 before the decimal point).

===== =========================================== ========
Type  Characters Matched                          Output
===== =========================================== ========
l     Letters (ASCII)                             str
w     Letters, numbers and underscore             str
W     Not letters, numbers and underscore         str
s     Whitespace                                  str
S     Non-whitespace                              str
d     Digits (effectively integer numbers)        int
D     Non-digit                                   str
n     Numbers with thousands separators (, or .)  int
%     Percentage (converted to value/100.0)       float
f     Fixed-point numbers                         float
F     Decimal numbers                             Decimal
e     Floating-point numbers with exponent        float
      e.g. 1.1e-10, NAN (all case insensitive)
g     General number format (either d, f or e)    float
b     Binary numbers                              int
o     Octal numbers                               int
x     Hexadecimal numbers (lower and upper case)  int
ti    ISO 8601 format date/time                   datetime
      e.g. 1972-01-20T10:21:36Z ("T" and "Z"
      optional)
te    RFC2822 e-mail format date/time             datetime
      e.g. Mon, 20 Jan 1972 10:21:36 +1000
tg    Global (day/month) format date/time         datetime
      e.g. 20/1/1972 10:21:36 AM +1:00
ta    US (month/day) format date/time             datetime
      e.g. 1/20/1972 10:21:36 PM +10:30
tc    ctime() format date/time                    datetime
      e.g. Sun Sep 16 01:03:52 1973
th    HTTP log format date/time                   datetime
      e.g. 21/Nov/2011:00:07:11 +0000
ts    Linux system log format date/time           datetime
      e.g. Nov  9 03:37:44
tt    Time                                        time
      e.g. 10:21:36 PM -5:30
===== =========================================== ========

Some examples of typed parsing with ``None`` returned if the typing
does not match:

.. code-block:: pycon

    >>> parse('Our {:d} {:w} are...', 'Our 3 weapons are...')
    <Result (3, 'weapons') {}>
    >>> parse('Our {:d} {:w} are...', 'Our three weapons are...')
    >>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM')
    <Result (datetime.datetime(2011, 2, 1, 23, 0),) {}>

And messing about with alignment:

.. code-block:: pycon

    >>> parse('with {:>} herring', 'with     a herring')
    <Result ('a',) {}>
    >>> parse('spam {:^} spam', 'spam    lovely     spam')
    <Result ('lovely',) {}>

Note that the "center" alignment does not test to make sure the value is
centered - it just strips leading and trailing whitespace.

Width and precision may be used to restrict the size of matched text
from the input. Width specifies a minimum size and precision specifies
a maximum. For example:

.. code-block:: pycon

    >>> parse('{:.2}{:.2}', 'look')           # specifying precision
    <Result ('lo', 'ok') {}>
    >>> parse('{:4}{:4}', 'look at that')     # specifying width
    <Result ('look', 'at that') {}>
    >>> parse('{:4}{:.4}', 'look at that')    # specifying both
    <Result ('look at ', 'that') {}>
    >>> parse('{:2d}{:2d}', '0440')           # parsing two contiguous numbers
    <Result (4, 40) {}>

Some notes for the date and time types:

- the presence of the time part is optional (including ISO 8601, starting
  at the "T"). A full datetime object will always be returned; the time
  will be set to 00:00:00. You may also specify a time without seconds.
- when a seconds amount is present in the input fractions will be parsed
  to give microseconds.
- except in ISO 8601 the day and month digits may be 0-padded.
- the date separator for the tg and ta formats may be "-" or "/".
- named months (abbreviations or full names) may be used in the ta and tg
  formats in place of numeric months.
- as per RFC 2822 the e-mail format may omit the day (and comma), and the
  seconds but nothing else.
- hours greater than 12 will be happily accepted.
- the AM/PM are optional, and if PM is found then 12 hours will be added
  to the datetime object's hours amount - even if the hour is greater
  than 12 (for consistency.)
- in ISO 8601 the "Z" (UTC) timezone part may be a numeric offset
- timezones are specified as "+HH:MM" or "-HH:MM". The hour may be one or two
  digits (0-padded is OK.) Also, the ":" is optional.
- the timezone is optional in all except the e-mail format (it defaults to
  UTC.)
- named timezones are not handled yet.

Note: attempting to match too many datetime fields in a single parse() will
currently result in a resource allocation issue. A TooManyFields exception
will be raised in this instance. The current limit is about 15. It is hoped
that this limit will be removed one day.

.. _`Format String Syntax`:
  http://docs.python.org/library/string.html#format-string-syntax
.. _`Format Specification Mini-Language`:
  http://docs.python.org/library/string.html#format-specification-mini-language


Result and Match Objects
------------------------

The result of a ``parse()`` and ``search()`` operation is either ``None`` (no match), a
``Result`` instance or a ``Match`` instance if ``evaluate_result`` is False.

The ``Result`` instance has three attributes:

``fixed``
   A tuple of the fixed-position, anonymous fields extracted from the input.
``named``
   A dictionary of the named fields extracted from the input.
``spans``
   A dictionary mapping the names and fixed position indices matched to a
   2-tuple slice range of where the match occurred in the input.
   The span does not include any stripped padding (alignment or width).

The ``Match`` instance has one method:

``evaluate_result()``
   Generates and returns a ``Result`` instance for this ``Match`` object.



Custom Type Conversions
-----------------------

If you wish to have matched fields automatically converted to your own type you
may pass in a dictionary of type conversion information to ``parse()`` and
``compile()``.

The converter will be passed the field string matched. Whatever it returns
will be substituted in the ``Result`` instance for that field.

Your custom type conversions may override the builtin types if you supply one
with the same identifier:

.. code-block:: pycon

    >>> def shouty(string):
    ...    return string.upper()
    ...
    >>> parse('{:shouty} world', 'hello world', dict(shouty=shouty))
    <Result ('HELLO',) {}>

If the type converter has the optional ``pattern`` attribute, it is used as
regular expression for better pattern matching (instead of the default one):

.. code-block:: pycon

    >>> def parse_number(text):
    ...    return int(text)
    >>> parse_number.pattern = r'\d+'
    >>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
    <Result () {'number': 42}>
    >>> _ = parse('Answer: {:Number}', 'Answer: Alice', dict(Number=parse_number))
    >>> assert _ is None, "MISMATCH"

You can also use the ``with_pattern(pattern)`` decorator to add this
information to a type converter function:

.. code-block:: pycon

    >>> from parse import with_pattern
    >>> @with_pattern(r'\d+')
    ... def parse_number(text):
    ...    return int(text)
    >>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
    <Result () {'number': 42}>

A more complete example of a custom type might be:

.. code-block:: pycon

    >>> yesno_mapping = {
    ...     "yes":  True,   "no":    False,
    ...     "on":   True,   "off":   False,
    ...     "true": True,   "false": False,
    ... }
    >>> @with_pattern(r"|".join(yesno_mapping))
    ... def parse_yesno(text):
    ...     return yesno_mapping[text.lower()]


If the type converter ``pattern`` uses regex-grouping (with parenthesis),
you should indicate this by using the optional ``regex_group_count`` parameter
in the ``with_pattern()`` decorator:

.. code-block:: pycon

    >>> @with_pattern(r'((\d+))', regex_group_count=2)
    ... def parse_number2(text):
    ...    return int(text)
    >>> parse('Answer: {:Number2} {:Number2}', 'Answer: 42 43', dict(Number2=parse_number2))
    <Result (42, 43) {}>

Otherwise, this may cause parsing problems with unnamed/fixed parameters.


Potential Gotchas
-----------------

``parse()`` will always match the shortest text necessary (from left to right)
to fulfil the parse pattern, so for example:


.. code-block:: pycon

    >>> pattern = '{dir1}/{dir2}'
    >>> data = 'root/parent/subdir'
    >>> sorted(parse(pattern, data).named.items())
    [('dir1', 'root'), ('dir2', 'parent/subdir')]

So, even though `{'dir1': 'root/parent', 'dir2': 'subdir'}` would also fit
the pattern, the actual match represents the shortest successful match for
``dir1``.

----

- 1.19.0 Added slice access to fixed results (thanks @jonathangjertsen).
  Also corrected matching of *full string* vs. *full line* (thanks @giladreti)
  Fix issue with using digit field numbering and types
- 1.18.0 Correct bug in int parsing introduced in 1.16.0 (thanks @maxxk)
- 1.17.0 Make left- and center-aligned search consume up to next space
- 1.16.0 Make compiled parse objects pickleable (thanks @martinResearch)
- 1.15.0 Several fixes for parsing non-base 10 numbers (thanks @vladikcomper)
- 1.14.0 More broad acceptance of Fortran number format (thanks @purpleskyfall)
- 1.13.1 Project metadata correction.
- 1.13.0 Handle Fortran formatted numbers with no leading 0 before decimal
  point (thanks @purpleskyfall).
  Handle comparison of FixedTzOffset with other types of object.
- 1.12.1 Actually use the `case_sensitive` arg in compile (thanks @jacquev6)
- 1.12.0 Do not assume closing brace when an opening one is found (thanks @mattsep)
- 1.11.1 Revert having unicode char in docstring, it breaks Bamboo builds(?!)
- 1.11.0 Implement `__contains__` for Result instances.
- 1.10.0 Introduce a "letters" matcher, since "w" matches numbers
  also.
- 1.9.1 Fix deprecation warnings around backslashes in regex strings
  (thanks Mickael Schoentgen). Also fix some documentation formatting
  issues.
- 1.9.0 We now honor precision and width specifiers when parsing numbers
  and strings, allowing parsing of concatenated elements of fixed width
  (thanks Julia Signell)
- 1.8.4 Add LICENSE file at request of packagers.
  Correct handling of AM/PM to follow most common interpretation.
  Correct parsing of hexadecimal that looks like a binary prefix.
  Add ability to parse case sensitively.
  Add parsing of numbers to Decimal with "F" (thanks John Vandenberg)
- 1.8.3 Add regex_group_count to with_pattern() decorator to support
  user-defined types that contain brackets/parenthesis (thanks Jens Engel)
- 1.8.2 add documentation for including braces in format string
- 1.8.1 ensure bare hexadecimal digits are not matched
- 1.8.0 support manual control over result evaluation (thanks Timo Furrer)
- 1.7.0 parse dict fields (thanks Mark Visser) and adapted to allow
  more than 100 re groups in Python 3.5+ (thanks David King)
- 1.6.6 parse Linux system log dates (thanks Alex Cowan)
- 1.6.5 handle precision in float format (thanks Levi Kilcher)
- 1.6.4 handle pipe "|" characters in parse string (thanks Martijn Pieters)
- 1.6.3 handle repeated instances of named fields, fix bug in PM time
  overflow
- 1.6.2 fix logging to use local, not root logger (thanks Necku)
- 1.6.1 be more flexible regarding matched ISO datetimes and timezones in
  general, fix bug in timezones without ":" and improve docs
- 1.6.0 add support for optional ``pattern`` attribute in user-defined types
  (thanks Jens Engel)
- 1.5.3 fix handling of question marks
- 1.5.2 fix type conversion error with dotted names (thanks Sebastian Thiel)
- 1.5.1 implement handling of named datetime fields
- 1.5 add handling of dotted field names (thanks Sebastian Thiel)
- 1.4.1 fix parsing of "0" in int conversion (thanks James Rowe)
- 1.4 add __getitem__ convenience access on Result.
- 1.3.3 fix Python 2.5 setup.py issue.
- 1.3.2 fix Python 3.2 setup.py issue.
- 1.3.1 fix a couple of Python 3.2 compatibility issues.
- 1.3 added search() and findall(); removed compile() from ``import *``
  export as it overwrites builtin.
- 1.2 added ability for custom and override type conversions to be
  provided; some cleanup
- 1.1.9 to keep things simpler number sign is handled automatically;
  significant robustification in the face of edge-case input.
- 1.1.8 allow "d" fields to have number base "0x" etc. prefixes;
  fix up some field type interactions after stress-testing the parser;
  implement "%" type.
- 1.1.7 Python 3 compatibility tweaks (2.5 to 2.7 and 3.2 are supported).
- 1.1.6 add "e" and "g" field types; removed redundant "h" and "X";
  removed need for explicit "#".
- 1.1.5 accept textual dates in more places; Result now holds match span
  positions.
- 1.1.4 fixes to some int type conversion; implemented "=" alignment; added
  date/time parsing with a variety of formats handled.
- 1.1.3 type conversion is automatic based on specified field types. Also added
  "f" and "n" types.
- 1.1.2 refactored, added compile() and limited ``from parse import *``
- 1.1.1 documentation improvements
- 1.1.0 implemented more of the `Format Specification Mini-Language`_
  and removed the restriction on mixing fixed-position and named fields
- 1.0.0 initial release

This code is copyright 2012-2021 Richard Jones <richard@python.org>
See the end of the source file for the license of use.
    )absolute_importz1.19.0N)datetimetimetzinfo	timedelta)Decimal)partialz!parse search findall with_patternc                    s    fdd}|S )ae  Attach a regular expression pattern matcher to a custom type converter
    function.

    This annotates the type converter with the :attr:`pattern` attribute.

    EXAMPLE:
        >>> import parse
        >>> @parse.with_pattern(r"\d+")
        ... def parse_number(text):
        ...     return int(text)

    is equivalent to:

        >>> def parse_number(text):
        ...     return int(text)
        >>> parse_number.pattern = r"\d+"

    :param pattern: regular expression pattern (as text)
    :param regex_group_count: Indicates how many regex-groups are in pattern.
    :return: wrapped function
    c                    s    | _ | _| S Npatternregex_group_count)funcr
    0/usr/local/lib/python3.10/dist-packages/parse.py	decorator  s   zwith_pattern.<locals>.decoratorr   )r   r   r   r   r
   r   with_pattern  s   r   c                   @   s&   e Zd ZdZdZdddZdd ZdS )	int_converta  Convert a string to an integer.

    The string may start with a sign.

    It may be of a base other than 2, 8, 10 or 16.

    If base isn't specified, it will be detected automatically based
    on a string format. When string starts with a base indicator, 0#nnnn,
    it overrides the default base of 10.

    It may also have other non-numeric characters that we can ignore.
    Z$0123456789abcdefghijklmnopqrstuvwxyzNc                 C   
   || _ d S r	   )base)selfr   r   r   r   __init__     
zint_convert.__init__c                 C   s   |d dkrd}d}n|d dkrd}d}nd}d}| j }|d u rQd}|| dkrQt|| dkrQ||d  d	v r<d}n||d  d
v rGd}n
||d  dv rQd}tjd | }td| d| }|t|| S )Nr   -   +
   0   ZbBZoO   xX   z[^%s] )r   lenr   CHARSresublowerint)r   stringmatchsignZnumber_startr   charsr   r   r   __call__  s*   zint_convert.__call__r	   )__name__
__module____qualname____doc__r$   r   r-   r   r   r   r   r     s
    
r   c                   @       e Zd ZdZdd Zdd ZdS )convert_firstzConvert the first element of a pair.
    This equivalent to lambda s,m: converter(s). But unlike a lambda function, it can be pickled
    c                 C   r   r	   	converter)r   r5   r   r   r   r   >  r   zconvert_first.__init__c                 C   s
   |  |S r	   r4   )r   r)   r*   r   r   r   r-   A  r   zconvert_first.__call__N)r.   r/   r0   r1   r   r-   r   r   r   r   r3   9  s    r3   c                 C   s   t | d d d S )Nr   g      Y@)float)r)   r*   r   r   r   
percentageE  s   r7   c                   @   sH   e Zd ZdZedZdd Zdd Zdd Zd	d
 Z	dd Z
dd ZdS )FixedTzOffsetz&Fixed offset in minutes east from UTC.r   c                 C   s   t |d| _|| _d S )N)minutes)r   _offset_name)r   offsetnamer   r   r   r   N  s   
zFixedTzOffset.__init__c                 C      d| j j| j| jf S )Nz
<%s %s %s>)	__class__r.   r;   r:   r   r   r   r   __repr__R     zFixedTzOffset.__repr__c                 C      | j S r	   )r:   r   dtr   r   r   	utcoffsetU     zFixedTzOffset.utcoffsetc                 C   rC   r	   )r;   rD   r   r   r   tznameX  rG   zFixedTzOffset.tznamec                 C   rC   r	   )ZEROrD   r   r   r   dst[  rG   zFixedTzOffset.dstc                 C   s&   t |tsdS | j|jko| j|jkS NF)
isinstancer8   r;   r:   )r   otherr   r   r   __eq__^  s   
zFixedTzOffset.__eq__N)r.   r/   r0   r1   r   rI   r   rA   rF   rH   rJ   rN   r   r   r   r   r8   I  s    r8   Janr   JanuaryFebr   FebruaryMar   ZMarchApr   ZAprilMay   Jun   ZJuneJul   ZJulyAugr   ZAugustSep	   Z	SeptemberOctr   ZOctoberNov   ZNovemberDec   ZDecemberz(Mon|Tue|Wed|Thu|Fri|Sat|Sun)z1(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(%s)|z$(\d{1,2}:\d{1,2}(:\d{1,2}(\.\d+)?)?)z
(\s+[AP]M)z(\s+[-+]\d\d?:?\d\d)c              
   C   s  |  }d}|	r|
rt j}||	 }||
 }nH|dur(td|| \}}}n8|dur8td|| \}}}n(|durHtd|| \}}}n|dur^|\}}}|| }|| }|| }nd}d } } }}|dur|| r|| d}t|dkr|\}}n|\}}}d|v r|d\}}ttd| d	 }t|}t|}t|}|dur|| }|r|	 }|d
kr|dkr|d8 }n|dkr|dkrn|dkr|d7 }|dur|| }|dkrt
dd}nX|r>|	 }| rnL|d }d|v r|dd d\}}n t|dkr|d |dd }}n|dd |dd }}t|t|d  }|dkr9| }t
||}|rLt|||||d}|S t|}| rZt|}nt| }t|}t||||||||d}|S )z_Convert the incoming string containing some date / time info into a
    datetime instance.
    FNz[-/\s]Tr   :r   .i@B ZAMrd   ZPMZUTCr   rV   rT   rX   <   r   )r   )groupsr   todayyearr%   splitr#   r(   r6   stripr8   isupperr   isdigit
MONTHS_MAP)r)   r*   ymdmdydmyd_m_yhmsamtzmmddrl   Z	time_onlyymdHMSutr+   ZtzhZtzmr<   r   r   r   date_convert  s   












r   c                   @      e Zd ZdS )TooManyFieldsNr.   r/   r0   r   r   r   r   r         r   c                   @   r   )RepeatedNameErrorNr   r   r   r   r   r     r   r   z([?\\\\.[\]()*+\^$!\|])znbox%fFegwWdDsSlc                 C   s   g | ]}d | qS )r   r   ).0cr   r   r   
<listcomp>  s    r   Zieahgctsc                 C   s&  d }}| d dv r| d }| dd } nt | dkr/| d dv r/| d }| d }| dd } d}| rA| d dkrAd}| dd } d	}| rZ| d  sLn|| d 7 }| dd } | sE| d
r~| dd } d	}| r~| d  spn|| d 7 }| dd } | si| }|r|tvr||vrtd| t S )z?Pull apart the format [[fill]align][0][width][.precision][type]Nr   z<>=^r   r   Fr   Tr"   rh   zformat spec %r not recognised)r#   rr   
startswithALLOWED_TYPES
ValueErrorlocals)formatextra_typesfillalignzerowidth	precisiontyper   r   r   extract_format  s@   
r   z5({{|}}|{\w*(?:(?:\.\w+)|(?:\[[^\]]+\]))*(?::[^}]+)?})c                   @   s   e Zd ZdZd$ddZdd Zedd	 Zed
d Zedd Z	edd Z
d%ddZd&ddZ	d'ddZdd Zdd Zdd Zdd Zd d! Zd"d# ZdS )(ParserzDEncapsulate a format string that may be used to parse other strings.NFc                 C   s   i | _ i | _i | _|| _|d u ri }|| _|rtj| _ntjtjB | _g | _	g | _
d| _i | _|  | _d | _d | _td|| j d S )Nr   zformat %r -> %r)_group_to_name_map_name_to_group_map_name_types_format_extra_typesr%   DOTALL	_re_flags
IGNORECASE_fixed_fields_named_fields_group_index_type_conversions_generate_expression_expression_Parser__search_re_Parser__match_relogdebug)r   r   r   case_sensitiver   r   r   r   (  s$   

zParser.__init__c                 C   s>   t | jdkrd| jj| jd d d f S d| jj| jf S )N   z<%s %r>   z...)r#   r   r?   r.   r@   r   r   r   rA   G  s   zParser.__repr__c                 C   sd   | j d u r/zt| j| j| _ W | j S  ty.   tt d }|	dr*t
dY | j S w | j S )Nr   +this version only supports 100 named groups:sorry, you are attempting to parse too many complex fields)r   r%   compiler   r   AssertionErrorstrsysexc_infoendswithr   )r   er   r   r   
_search_reL  s   

zParser._search_rec                 C   s   | j d u r@d| j }zt|| j| _ W | j S  ty2   tt d }|	dr.t
dY | j S  tjy?   td| w | j S )Nz\A%s\Zr   r   r   zVGroup names (e.g. (?P<name>) can cause failure, as they are not escaped properly: '%s')r   r   r%   r   r   r   r   r   r   r   r   errorNotImplementedError)r   Z
expressionr   r   r   r   	_match_reZ  s*   


	zParser._match_rec                 C   
   | j  S r	   )r   copyr@   r   r   r   named_fieldsn     
zParser.named_fieldsc                 C   r   r	   )r   r   r@   r   r   r   fixed_fieldsr  r   zParser.fixed_fieldsTc                 C   s0   | j |}|du rdS |r| |S t| |S )zwMatch my format to the string exactly.

        Return a Result or Match instance or None if there's no match.
        N)r   r*   evaluate_resultMatch)r   r)   r   r~   r   r   r   parsev  s   

zParser.parser   c                 C   sD   |du rt |}| j|||}|du rdS |r| |S t| |S )a  Search the string for my format.

        Optionally start the search at "pos" character index and limit the
        search to a maximum index of endpos - equivalent to
        search(string[:endpos]).

        If the ``evaluate_result`` argument is set to ``False`` a
        Match instance is returned instead of the actual Result instance.

        Return either a Result instance or None if there's no match.
        N)r#   r   searchr   r   )r   r)   posendposr   r~   r   r   r   r     s   

zParser.searchc                 C   s"   |du rt |}t| ||||dS )aI  Search "string" for all occurrences of "format".

        Optionally start the search at "pos" character index and limit the
        search to a maximum index of endpos - equivalent to
        search(string[:endpos]).

        Returns an iterator that holds Result or Match instances for each format match
        found.
        Nr   )r#   ResultIterator)r   r)   r   r   r   r   r   r   r   findall  s
   
zParser.findallc           
      C   sl   i }|  D ]-\}}td| \}}|}|}|r/td|D ]}	||i }|	dd }q |||< q|S )Nz([^\[]+)(.*)z
\[[^\]]+\]r   r   )itemsr%   r*   rl   r   
setdefault)
r   r   resultfieldvaluebasenameZsubkeysr   ksubkeyr   r   r   _expand_named_fields  s   
zParser._expand_named_fieldsc           	         s   t   | jD ]}|| jv r| j|  |  |< q	t fdd| jD   }i }i | jD ]#}| j| }||< || jv rO| j| || }n|| }|||< q4tfdd|D }|	fddt
| jD  t | ||S )z;Generate a Result instance for the given regex match objectc                 3   s    | ]} | V  qd S r	   r   r   n)r   r   r   	<genexpr>  s    z)Parser.evaluate_result.<locals>.<genexpr>c                 3   s"    | ]}|  | fV  qd S r	   spanr   )r~   name_mapr   r   r     s     c                 3   s&    | ]\}}|  |d  fV  qdS )r   Nr   )r   ir   )r~   r   r   r     s   $ )listrl   r   r   tuple	groupdictr   r   dictupdate	enumerateResultr   )	r   r~   r   r   r   r   Zkorigr   spansr   )r   r~   r   r   r     s&   





zParser.evaluate_resultc                 C   s   d| d S )N\r   )group)r   r*   r   r   r   _regex_replace  s   zParser._regex_replacec                 C   s   g }t | jD ]8}|sq|dkr|d q|dkr!|d q|d dkr6|d dkr6|| | q|t| j| qd	|S )
Nz{{z\{z}}z\}r   {r   }r"   )	PARSE_REro   r   append_handle_fieldREGEX_SAFETYr&   r   join)r   r   partr   r   r   r     s   
zParser._generate_expressionc                 C   s   | dd dd dd}d}|| jv r?|d7 }d|v r&| dd| }nd|v r3| dd| }ntd|f || jv s|| j|< || j|< |S )Nrh   _[]r   zduplicated group name %r)replacer   KeyErrorr   )r   r   r   r   r   r   r   _to_group_name  s   




zParser._to_group_namec                 C   s  |dd }d}d|v r| d\}}n|}|rT|d  rT|| jv r?| j| |kr6td||| j| f | j| }d| S | |}|| j|< | j| d| }n| j| j	 d	}| j	}|sm|  j	d7  _	|d
 S t
|| j}|d }|o||dv }|| jv r| j| }t|dd
}	t|dd}
|
d u rd}
|  j	|
7  _	t|| j|< n`|dkrd}	|  j	d7  _	td| j|< nJ|dkrd}	td| j|< |  j	d7  _	n4|dkrd}	td| j|< |  j	d7  _	n|dkrd}	td| j|< |  j	d7  _	n|dkrd}	|  j	d7  _	t| j|< n|dkr'd}	tt| j|< n|dkr7d}	tt| j|< n|d krGd!}	tt| j|< n|d"kr^d#}	|  j	d7  _	tt| j|< n|d$kr|d%rrd&t|d%  }nd'}d(j|d)}	t | j|< n|d*krd+t }	| j	}tt|d |d, |d- d.| j|< |  j	d-7  _	na|d/krd0ttttf }	| j	}tt|d |d1 |d |d2 d3| j|< |  j	d27  _	n4|d4krd5ttttf }	| j	}tt|d |d1 |d |d2 d6| j|< |  j	d27  _	n|d7kr+d8ttttf }	| j	}tt|d9 |d1 |d d:| j|< |  j	d7  _	n|d;krSd<tttf }	| j	}tt|d |d9 |d= d:| j|< |  j	d=7  _	n|d>krd?tttf }	| j	}tt|d, |d9 |d f|d1 d@| j|< |  j	d7  _	n|dAkrdBtttf }	| j	}tt|d |d, |d1 dC| j|< |  j	d17  _	nb|dDkrdEt }	| j	}tt|d |d9 |d1 dF| j|< |  j	d17  _	n=|dGkrdH}	n5|rdI| }	n-|dJr|d%rdK|d% |dJ f }	ndL|dJ  }	n|d%rdM|d%  }	nd
}	|dN }|dO }|r(|dPkr$|sdQ}dR| |	 }	dS|	 }	|s-dT}|r;||	 }	|  j	d7  _	|d% rE|sEdU}|dVv rNdW| }|dXkr[dY|	|f }	|	S |dUkrhdZ||	f }	|	S |d[krtd\||	|f }	|	S )]Nr   r   r"   rg   r   zAfield type %r for field "%s" does not match previous seen type %rz(?P=%s)z(?P<%s>%%s)re   z.+?r   z	n%fegdobxr   r   r   z\d{1,3}([,.]\d{3})*r   bz(0[bB])?[01]+r   oz(0[oO])?[0-7]+r   xz(0[xX])?[0-9a-fA-F]+r!   %z\d+(\.\d+)?%fz\d*\.\d+Fr   z.\d*\.\d+[eE][-+]?\d+|nan|NAN|[-+]?inf|[-+]?INFgz4\d+(\.\d+)?([eE][-+]?\d+)?|nan|NAN|[-+]?inf|[-+]?INFr   r   z{1,%s}r   zF\d{w}|[-+ ]?0[xX][0-9a-fA-F]{w}|[-+ ]?0[bB][01]{w}|[-+ ]?0[oO][0-7]{w})wtiz3(\d{4}-\d\d-\d\d)((\s+|T)%s)?(Z|\s*[-+]\d\d:?\d\d)?rV   r\   )rt   rx   rz   tgz0(\d{1,2}[-/](\d{1,2}|%s)[-/]\d{4})(\s+%s)?%s?%s?rX   r_   )rv   rx   ry   rz   taz0((\d{1,2}|%s)[-/]\d{1,2}[-/]\d{4})(\s+%s)?%s?%s?)ru   rx   ry   rz   tez&(%s,\s+)?(\d{1,2}\s+%s\s+\d{4})\s+%s%srT   )rv   rx   rz   thz(\d{1,2}[-/]%s[-/]\d{4}):%s%srZ   Ztcz$(%s)\s+%s\s+(\d{1,2})\s+%s\s+(\d{4}))rw   rx   ttz	%s?%s?%s?)rx   ry   rz   tsz+%s(\s+)(\d+)(\s+)(\d{1,2}:\d{1,2}:\d{1,2})?)r{   r|   rx   lz	[A-Za-z]+z\%s+r   z	.{%s,%s}?z.{1,%s}?z.{%s,}?r   r   =r   z%s*z[-+ ]? >z.\+?*[](){}^$r   <z%s%s+z%s*%s^z%s*%s%s+)ro   isalphar   r   r   r   r   r   r   r   r   r   getattrr3   r   r   r7   r6   r   getr(   r   TIME_PATr   r   ALL_MONTHS_PATAM_PATTZ_PATDAYS_PAT
MONTHS_PAT)r   r   r   r=   r   wrapr   Z
is_numericZtype_convertersr   r   r   r   r   r   r   r   r   	  s  





























zParser._handle_fieldrK   T)r   NT)r   NNT)r.   r/   r0   r1   r   rA   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   %  s,    







r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )r   a  The result of a parse() or search().

    Fixed results may be looked up using `result[index]`.
    Slices of fixed results may also be looked up.

    Named results may be looked up using `result['name']`.

    Named results may be tested for existence using `'name' in result`.
    c                 C   s   || _ || _|| _d S r	   )fixednamedr   )r   r  r  r   r   r   r   r     s   
zResult.__init__c                 C   s"   t |ttfr| j| S | j| S r	   )rL   r(   slicer  r  )r   itemr   r   r   __getitem__	  s   

zResult.__getitem__c                 C   r>   )Nz
<%s %r %r>)r?   r.   r  r  r@   r   r   r   rA     rB   zResult.__repr__c                 C   s
   || j v S r	   )r  )r   r=   r   r   r   __contains__  r   zResult.__contains__N)r.   r/   r0   r1   r   r  rA   r  r   r   r   r   r     s    
r   c                   @   r2   )r   zThe result of a parse() or search() if no results are generated.

    This class is only used to expose internal used regex match objects
    to the user and use them for external Parser.evaluate_result calls.
    c                 C   s   || _ || _d S r	   )parserr*   )r   r  r*   r   r   r   r     s   
zMatch.__init__c                 C   s   | j | jS )zGenerate results for this Match)r  r   r*   r@   r   r   r   r      s   zMatch.evaluate_resultN)r.   r/   r0   r1   r   r   r   r   r   r   r     s    r   c                   @   s.   e Zd ZdZd
ddZdd Zdd ZeZd	S )r   zQThe result of a findall() operation.

    Each element is a Result instance.
    Tc                 C   s"   || _ || _|| _|| _|| _d S r	   )r  r)   r   r   r   )r   r  r)   r   r   r   r   r   r   r   +  s
   
zResultIterator.__init__c                 C   s   | S r	   r   r@   r   r   r   __iter__2  s   zResultIterator.__iter__c                 C   sN   | j j| j| j| j}|d u rt | | _| jr!| j |S t	| j |S r	   )
r  r   r   r)   r   r   StopIterationendr   r   )r   r~   r   r   r   __next__5  s   
zResultIterator.__next__Nr  )r.   r/   r0   r1   r   r  r!  nextr   r   r   r   r   %  s    
r   TFc                 C   s   t | ||d}|j||dS )a  Using "format" attempt to pull values from "string".

    The format must match the string contents exactly. If the value
    you're looking for is instead just a part of the string use
    search().

    If ``evaluate_result`` is True the return value will be an Result instance with two attributes:

     .fixed - tuple of fixed-position values from the string
     .named - dict of named values from the string

    If ``evaluate_result`` is False the return value will be a Match instance with one method:

     .evaluate_result() - This will return a Result instance like you would get
                          with ``evaluate_result`` set to True

    The default behaviour is to match strings case insensitively. You may match with
    case by specifying case_sensitive=True.

    If the format is invalid a ValueError will be raised.

    See the module documentation for the use of "extra_types".

    In the case there is no match parse() will return None.
    r   r   r   )r   r   )r   r)   r   r   r   pr   r   r   r   D  s   r   c                 C       t | ||d}|j||||dS )a]  Search "string" for the first occurrence of "format".

    The format may occur anywhere within the string. If
    instead you wish for the format to exactly match the string
    use parse().

    Optionally start the search at "pos" character index and limit the search
    to a maximum index of endpos - equivalent to search(string[:endpos]).

    If ``evaluate_result`` is True the return value will be an Result instance with two attributes:

     .fixed - tuple of fixed-position values from the string
     .named - dict of named values from the string

    If ``evaluate_result`` is False the return value will be a Match instance with one method:

     .evaluate_result() - This will return a Result instance like you would get
                          with ``evaluate_result`` set to True

    The default behaviour is to match strings case insensitively. You may match with
    case by specifying case_sensitive=True.

    If the format is invalid a ValueError will be raised.

    See the module documentation for the use of "extra_types".

    In the case there is no match parse() will return None.
    r#  r   )r   r   r   r)   r   r   r   r   r   r$  r   r   r   r   b  s   %r   c                 C   r%  )a  Search "string" for all occurrences of "format".

    You will be returned an iterator that holds Result instances
    for each format match found.

    Optionally start the search at "pos" character index and limit the search
    to a maximum index of endpos - equivalent to search(string[:endpos]).

    If ``evaluate_result`` is True each returned Result instance has two attributes:

     .fixed - tuple of fixed-position values from the string
     .named - dict of named values from the string

    If ``evaluate_result`` is False each returned value is a Match instance with one method:

     .evaluate_result() - This will return a Result instance like you would get
                          with ``evaluate_result`` set to True

    The default behaviour is to match strings case insensitively. You may match with
    case by specifying case_sensitive=True.

    If the format is invalid a ValueError will be raised.

    See the module documentation for the use of "extra_types".
    r#  r   )r   r   r&  r   r   r   r     s   "r   c                 C   s   t | ||dS )a  Create a Parser instance to parse "format".

    The resultant Parser has a method .parse(string) which
    behaves in the same manner as parse(format, string).

    The default behaviour is to match strings case insensitively. You may match with
    case by specifying case_sensitive=True.

    Use this function if you intend to parse many strings
    with the same format.

    See the module documentation for the use of "extra_types".

    Returns a Parser instance.
    r#  )r   )r   r   r   r   r   r   r     s   r   r	   r   )	NNNNNNNNN)NTF)r   NNTFrK   )5r1   
__future__r   __version__r%   r   r   r   r   r   decimalr   	functoolsr   loggingro   __all__	getLoggerr.   r   r   r   r3   r7   r8   r   rs   r  r  r   r  r  r  r  r   r   r   r   r   r   setr   r   r   r   objectr   r   r   r   r   r   r   r   r   r   r   <module>   s       X

3	

c

*   W
!
,
&