pax_global_header00006660000000000000000000000064146317524720014525gustar00rootroot0000000000000052 comment=334db144c2813e9029cb890bbd49edd30f67ab9b r1chardj0n3s-parse-334db14/000077500000000000000000000000001463175247200153655ustar00rootroot00000000000000r1chardj0n3s-parse-334db14/.git-blame-ignore-revs000066400000000000000000000001071463175247200214630ustar00rootroot000000000000004cc9e9f398b8b80e6f0a68d25774cb1c0c32f2fb # black string normalization r1chardj0n3s-parse-334db14/.github/000077500000000000000000000000001463175247200167255ustar00rootroot00000000000000r1chardj0n3s-parse-334db14/.github/SECURITY.md000066400000000000000000000005141463175247200205160ustar00rootroot00000000000000# Security Policy ## Reporting a Vulnerability Security concerns may be reported to **[wim.glenn@gmail.com](mailto:wim.glenn+parse@gmail.com)**. Please provide the following information in your report: - A description of the vulnerability and its impact - How to reproduce the issue - Which versions of the library are affected r1chardj0n3s-parse-334db14/.github/workflows/000077500000000000000000000000001463175247200207625ustar00rootroot00000000000000r1chardj0n3s-parse-334db14/.github/workflows/test.yml000066400000000000000000000032271463175247200224700ustar00rootroot00000000000000name: parse on: push: branches: - master pull_request: branches: - master jobs: run-test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: - "3.8" - "3.9" - "3.10" - "3.11" - "3.12" - "pypy-3.9" steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Run tests run: | pip install -r tests/requirements.txt --editable . pytest - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: token: ${{ secrets.CODECOV_TOKEN }} tests-37: name: Python 3.7 on ubuntu-20.04 runs-on: ubuntu-20.04 container: image: python:3.7 steps: - uses: actions/checkout@v3 - name: Run tests run: | pip install -r tests/requirements.txt python -m pytest - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: token: ${{ secrets.CODECOV_TOKEN }} tests-27: name: Python 2.7 on ubuntu-20.04 runs-on: ubuntu-20.04 container: image: python:2.7-buster steps: - uses: actions/checkout@v3 - name: Run tests run: | pip install -r tests/requirements.txt python -m pytest - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: token: ${{ secrets.CODECOV_TOKEN }} r1chardj0n3s-parse-334db14/.gitignore000077500000000000000000000002261463175247200173600ustar00rootroot00000000000000venv *.pyc *.pyo .vscode/ .cache/ .idea/ .tox/ __pycache__/ .coverage .pytest_cache parse.egg-info .python-version MANIFEST build dist .ropeproject r1chardj0n3s-parse-334db14/.pytest.ini000066400000000000000000000001771463175247200175010ustar00rootroot00000000000000[pytest] addopts = --cov=parse --cov-report=term-missing --cov-append --cov-branch --doctest-modules --doctest-glob=README.rst r1chardj0n3s-parse-334db14/LICENSE000066400000000000000000000020751463175247200163760ustar00rootroot00000000000000Copyright (c) 2012-2019 Richard Jones Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. r1chardj0n3s-parse-334db14/README.rst000066400000000000000000000474371463175247200170730ustar00rootroot00000000000000Installation ------------ .. code-block:: pycon pip install parse Usage ----- 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!") >>> _[0] 'spam' Or to search a string for some pattern: .. code-block:: pycon >>> search('Age: {:d}\n', 'Name: Rufus\nAge: 42\nColor: red\n') Or find all the occurrences of some pattern in a string: .. code-block:: pycon >>> ''.join(r[0] for r in findall(">{}<", "

the bold text

")) '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) >>> p.parse("It's spam, I love it!") ("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(): https://docs.python.org/3/library/stdtypes.html#str.format 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") >>> r = parse("The {} who {} {}", "The knights who say Ni!") >>> print(r) >>> 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) >>> 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) >>> 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) >>> 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][sign][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. A sign specifier can be given, but has no effect. - 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 ===== =========================================== ======== The type can also be a datetime format string, following the `1989 C standard format codes`_, e.g. ``%Y-%m-%d``. Depending on the directives contained in the format string, parsed output may be an instance of ``datetime.datetime``, ``datetime.time``, or ``datetime.date``. .. code-block:: pycon >>> parse("{:%Y-%m-%d %H:%M:%S}", "2023-11-23 12:56:47") >>> parse("{:%H:%M}", "10:26") >>> parse("{:%Y/%m/%d}", "2023/11/25") 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...') >>> parse('Our {:d} {:w} are...', 'Our three weapons are...') >>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM') And messing about with alignment: .. code-block:: pycon >>> parse('with {:>} herring', 'with a herring') >>> parse('spam {:^} spam', 'spam lovely spam') 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 >>> parse('{:4}{:4}', 'look at that') # specifying width >>> parse('{:4}{:.4}', 'look at that') # specifying both >>> parse('{:2d}{:2d}', '0440') # parsing two contiguous numbers Some notes for the special 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`: https://docs.python.org/3/library/string.html#format-string-syntax .. _`Format Specification Mini-Language`: https://docs.python.org/3/library/string.html#format-specification-mini-language .. _`1989 C standard format codes`: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes 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', {"shouty": shouty}) 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', {"Number": parse_number}) >>> _ = parse('Answer: {:Number}', 'Answer: Alice', {"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', {"Number": parse_number}) 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', {"Number2": parse_number2}) 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``. Developers ---------- Want to contribute to parse? Fork the repo to your own GitHub account, and create a pull-request. .. code-block:: bash git clone git@github.com:r1chardj0n3s/parse.git git remote rename origin upstream git remote add origin git@github.com:YOURUSERNAME/parse.git git checkout -b myfeature To run the tests locally: .. code-block:: bash python -m venv .venv source .venv/bin/activate pip install -r tests/requirements.txt pip install -e . pytest ---- Changelog --------- - 1.20.2 Template field names can now contain - character i.e. HYPHEN-MINUS, chr(0x2d) - 1.20.1 The `%f` directive accepts 1-6 digits, like strptime (thanks @bbertincourt) - 1.20.0 Added support for strptime codes (thanks @bendichter) - 1.19.1 Added support for sign specifiers in number formats (thanks @anntzer) - 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 See the end of the source file for the license of use. r1chardj0n3s-parse-334db14/parse.py000066400000000000000000001053121463175247200170530ustar00rootroot00000000000000from __future__ import absolute_import import logging import re import sys from datetime import datetime from datetime import time from datetime import timedelta from datetime import tzinfo from decimal import Decimal from functools import partial __version__ = "1.20.2" __all__ = ["parse", "search", "findall", "with_pattern"] log = logging.getLogger(__name__) def with_pattern(pattern, regex_group_count=None): r"""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 """ def decorator(func): func.pattern = pattern func.regex_group_count = regex_group_count return func return decorator class int_convert: """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. """ CHARS = "0123456789abcdefghijklmnopqrstuvwxyz" def __init__(self, base=None): self.base = base def __call__(self, string, match): if string[0] == "-": sign = -1 number_start = 1 elif string[0] == "+": sign = 1 number_start = 1 else: sign = 1 number_start = 0 base = self.base # If base wasn't specified, detect it automatically if base is None: # Assume decimal number, unless different base is detected base = 10 # For number formats starting with 0b, 0o, 0x, use corresponding base ... if string[number_start] == "0" and len(string) - number_start > 2: if string[number_start + 1] in "bB": base = 2 elif string[number_start + 1] in "oO": base = 8 elif string[number_start + 1] in "xX": base = 16 chars = int_convert.CHARS[:base] string = re.sub("[^%s]" % chars, "", string.lower()) return sign * int(string, base) class convert_first: """Convert the first element of a pair. This equivalent to lambda s,m: converter(s). But unlike a lambda function, it can be pickled """ def __init__(self, converter): self.converter = converter def __call__(self, string, match): return self.converter(string) def percentage(string, match): return float(string[:-1]) / 100.0 class FixedTzOffset(tzinfo): """Fixed offset in minutes east from UTC.""" ZERO = timedelta(0) def __init__(self, offset, name): self._offset = timedelta(minutes=offset) self._name = name def __repr__(self): return "<%s %s %s>" % (self.__class__.__name__, self._name, self._offset) def utcoffset(self, dt): return self._offset def tzname(self, dt): return self._name def dst(self, dt): return self.ZERO def __eq__(self, other): if not isinstance(other, FixedTzOffset): return NotImplemented return self._name == other._name and self._offset == other._offset MONTHS_MAP = { "Jan": 1, "January": 1, "Feb": 2, "February": 2, "Mar": 3, "March": 3, "Apr": 4, "April": 4, "May": 5, "Jun": 6, "June": 6, "Jul": 7, "July": 7, "Aug": 8, "August": 8, "Sep": 9, "September": 9, "Oct": 10, "October": 10, "Nov": 11, "November": 11, "Dec": 12, "December": 12, } DAYS_PAT = r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun)" MONTHS_PAT = r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" ALL_MONTHS_PAT = r"(%s)" % "|".join(MONTHS_MAP) TIME_PAT = r"(\d{1,2}:\d{1,2}(:\d{1,2}(\.\d+)?)?)" AM_PAT = r"(\s+[AP]M)" TZ_PAT = r"(\s+[-+]\d\d?:?\d\d)" def date_convert( string, match, ymd=None, mdy=None, dmy=None, d_m_y=None, hms=None, am=None, tz=None, mm=None, dd=None, ): """Convert the incoming string containing some date / time info into a datetime instance. """ groups = match.groups() time_only = False if mm and dd: y = datetime.today().year m = groups[mm] d = groups[dd] elif ymd is not None: y, m, d = re.split(r"[-/\s]", groups[ymd]) elif mdy is not None: m, d, y = re.split(r"[-/\s]", groups[mdy]) elif dmy is not None: d, m, y = re.split(r"[-/\s]", groups[dmy]) elif d_m_y is not None: d, m, y = d_m_y d = groups[d] m = groups[m] y = groups[y] else: time_only = True H = M = S = u = 0 if hms is not None and groups[hms]: t = groups[hms].split(":") if len(t) == 2: H, M = t else: H, M, S = t if "." in S: S, u = S.split(".") u = int(float("." + u) * 1000000) S = int(S) H = int(H) M = int(M) if am is not None: am = groups[am] if am: am = am.strip() if am == "AM" and H == 12: # correction for "12" hour functioning as "0" hour: 12:15 AM = 00:15 by 24 hr clock H -= 12 elif am == "PM" and H == 12: # no correction needed: 12PM is midday, 12:00 by 24 hour clock pass elif am == "PM": H += 12 if tz is not None: tz = groups[tz] if tz == "Z": tz = FixedTzOffset(0, "UTC") elif tz: tz = tz.strip() if tz.isupper(): # TODO use the awesome python TZ module? pass else: sign = tz[0] if ":" in tz: tzh, tzm = tz[1:].split(":") elif len(tz) == 4: # 'snnn' tzh, tzm = tz[1], tz[2:4] else: tzh, tzm = tz[1:3], tz[3:5] offset = int(tzm) + int(tzh) * 60 if sign == "-": offset = -offset tz = FixedTzOffset(offset, tz) if time_only: d = time(H, M, S, u, tzinfo=tz) else: y = int(y) if m.isdigit(): m = int(m) else: m = MONTHS_MAP[m] d = int(d) d = datetime(y, m, d, H, M, S, u, tzinfo=tz) return d def strf_date_convert(x, _, type): is_date = any("%" + x in type for x in "aAwdbBmyYjUW") is_time = any("%" + x in type for x in "HIpMSfz") dt = datetime.strptime(x, type) if "%y" not in type and "%Y" not in type: # year not specified dt = dt.replace(year=datetime.today().year) if is_date and is_time: return dt elif is_date: return dt.date() elif is_time: return dt.time() else: ValueError("Datetime not a date nor a time?") # ref: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes dt_format_to_regex = { "%a": "(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)", "%A": "(?:Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)", "%w": "[0-6]", "%d": "[0-9]{1,2}", "%b": "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)", "%B": "(?:January|February|March|April|May|June|July|August|September|October|November|December)", "%m": "[0-9]{1,2}", "%y": "[0-9]{2}", "%Y": "[0-9]{4}", "%H": "[0-9]{1,2}", "%I": "[0-9]{1,2}", "%p": "(?:AM|PM)", "%M": "[0-9]{2}", "%S": "[0-9]{2}", "%f": "[0-9]{1,6}", "%z": "[+|-][0-9]{2}(:?[0-9]{2})?(:?[0-9]{2})?", # "%Z": punt "%j": "[0-9]{1,3}", "%U": "[0-9]{1,2}", "%W": "[0-9]{1,2}", } # Compile a regular expression pattern that matches any date/time format symbol. dt_format_symbols_re = re.compile("|".join(dt_format_to_regex)) def get_regex_for_datetime_format(format_): """ Generate a regex pattern for a given datetime format string. Parameters: format_ (str): The datetime format string. Returns: str: A regex pattern corresponding to the datetime format string. """ # Replace all format symbols with their regex patterns. return dt_format_symbols_re.sub(lambda m: dt_format_to_regex[m.group(0)], format_) class TooManyFields(ValueError): pass class RepeatedNameError(ValueError): pass # note: {} are handled separately REGEX_SAFETY = re.compile(r"([?\\.[\]()*+^$!|])") # allowed field types ALLOWED_TYPES = set(list("nbox%fFegwWdDsSl") + ["t" + c for c in "ieahgcts"]) def extract_format(format, extra_types): """Pull apart the format [[fill]align][sign][0][width][.precision][type]""" fill = align = None if format[0] in "<>=^": align = format[0] format = format[1:] elif len(format) > 1 and format[1] in "<>=^": fill = format[0] align = format[1] format = format[2:] if format.startswith(("+", "-", " ")): format = format[1:] zero = False if format and format[0] == "0": zero = True format = format[1:] width = "" while format: if not format[0].isdigit(): break width += format[0] format = format[1:] if format.startswith("."): # Precision isn't needed but we need to capture it so that # the ValueError isn't raised. format = format[1:] # drop the '.' precision = "" while format: if not format[0].isdigit(): break precision += format[0] format = format[1:] # the rest is the type, if present type = format if ( type and type not in ALLOWED_TYPES and type not in extra_types and not any(k in type for k in dt_format_to_regex) ): raise ValueError("format spec %r not recognised" % type) return locals() PARSE_RE = re.compile(r"({{|}}|{[\w-]*(?:\.[\w-]+|\[[^]]+])*(?::[^}]+)?})") class Parser(object): """Encapsulate a format string that may be used to parse other strings.""" def __init__(self, format, extra_types=None, case_sensitive=False): # a mapping of a name as in {hello.world} to a regex-group compatible # name, like hello__world. It's used to prevent the transformation of # name-to-group and group to name to fail subtly, such as in: # hello_.world-> hello___world->hello._world self._group_to_name_map = {} # also store the original field name to group name mapping to allow # multiple instances of a name in the format string self._name_to_group_map = {} # and to sanity check the repeated instances store away the first # field type specification for the named field self._name_types = {} self._format = format if extra_types is None: extra_types = {} self._extra_types = extra_types if case_sensitive: self._re_flags = re.DOTALL else: self._re_flags = re.IGNORECASE | re.DOTALL self._fixed_fields = [] self._named_fields = [] self._group_index = 0 self._type_conversions = {} self._expression = self._generate_expression() self.__search_re = None self.__match_re = None log.debug("format %r -> %r", format, self._expression) def __repr__(self): if len(self._format) > 20: return "<%s %r>" % (self.__class__.__name__, self._format[:17] + "...") return "<%s %r>" % (self.__class__.__name__, self._format) @property def _search_re(self): if self.__search_re is None: try: self.__search_re = re.compile(self._expression, self._re_flags) except AssertionError: # access error through sys to keep py3k and backward compat e = str(sys.exc_info()[1]) if e.endswith("this version only supports 100 named groups"): raise TooManyFields( "sorry, you are attempting to parse too many complex fields" ) return self.__search_re @property def _match_re(self): if self.__match_re is None: expression = r"\A%s\Z" % self._expression try: self.__match_re = re.compile(expression, self._re_flags) except AssertionError: # access error through sys to keep py3k and backward compat e = str(sys.exc_info()[1]) if e.endswith("this version only supports 100 named groups"): raise TooManyFields( "sorry, you are attempting to parse too many complex fields" ) except re.error: raise NotImplementedError( "Group names (e.g. (?P) can " "cause failure, as they are not escaped properly: '%s'" % expression ) return self.__match_re @property def named_fields(self): return self._named_fields[:] @property def fixed_fields(self): return self._fixed_fields[:] @property def format(self): return self._format def parse(self, string, evaluate_result=True): """Match my format to the string exactly. Return a Result or Match instance or None if there's no match. """ m = self._match_re.match(string) if m is None: return None if evaluate_result: return self.evaluate_result(m) else: return Match(self, m) def search(self, string, pos=0, endpos=None, evaluate_result=True): """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. """ if endpos is None: endpos = len(string) m = self._search_re.search(string, pos, endpos) if m is None: return None if evaluate_result: return self.evaluate_result(m) else: return Match(self, m) def findall( self, string, pos=0, endpos=None, extra_types=None, evaluate_result=True ): """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. """ if endpos is None: endpos = len(string) return ResultIterator( self, string, pos, endpos, evaluate_result=evaluate_result ) def _expand_named_fields(self, named_fields): result = {} for field, value in named_fields.items(): # split 'aaa[bbb][ccc]...' into 'aaa' and '[bbb][ccc]...' n = field.find("[") if n == -1: basename, subkeys = field, "" else: basename, subkeys = field[:n], field[n:] # create nested dictionaries {'aaa': {'bbb': {'ccc': ...}}} d = result k = basename if subkeys: for subkey in re.findall(r"\[[^]]+]", subkeys): d = d.setdefault(k, {}) k = subkey[1:-1] # assign the value to the last key d[k] = value return result def evaluate_result(self, m): """Generate a Result instance for the given regex match object""" # ok, figure the fixed fields we've pulled out and type convert them fixed_fields = list(m.groups()) for n in self._fixed_fields: if n in self._type_conversions: fixed_fields[n] = self._type_conversions[n](fixed_fields[n], m) fixed_fields = tuple(fixed_fields[n] for n in self._fixed_fields) # grab the named fields, converting where requested groupdict = m.groupdict() named_fields = {} name_map = {} for k in self._named_fields: korig = self._group_to_name_map[k] name_map[korig] = k if k in self._type_conversions: value = self._type_conversions[k](groupdict[k], m) else: value = groupdict[k] named_fields[korig] = value # now figure the match spans spans = {n: m.span(name_map[n]) for n in named_fields} spans.update((i, m.span(n + 1)) for i, n in enumerate(self._fixed_fields)) # and that's our result return Result(fixed_fields, self._expand_named_fields(named_fields), spans) def _regex_replace(self, match): return "\\" + match.group(1) def _generate_expression(self): # turn my _format attribute into the _expression attribute e = [] for part in PARSE_RE.split(self._format): if not part: continue elif part == "{{": e.append(r"\{") elif part == "}}": e.append(r"\}") elif part[0] == "{" and part[-1] == "}": # this will be a braces-delimited field to handle e.append(self._handle_field(part)) else: # just some text to match e.append(REGEX_SAFETY.sub(self._regex_replace, part)) return "".join(e) def _to_group_name(self, field): # return a version of field which can be used as capture group, even # though it might contain '.' group = field.replace(".", "_").replace("[", "_").replace("]", "_").replace("-", "_") # make sure we don't collide ("a.b" colliding with "a_b") n = 1 while group in self._group_to_name_map: n += 1 if "." in field: group = field.replace(".", "_" * n) elif "_" in field: group = field.replace("_", "_" * n) elif "-" in field: group = field.replace("-", "_" * n) else: raise KeyError("duplicated group name %r" % (field,)) # save off the mapping self._group_to_name_map[group] = field self._name_to_group_map[field] = group return group def _handle_field(self, field): # first: lose the braces field = field[1:-1] # now figure whether this is an anonymous or named field, and whether # there's any format specification format = "" if ":" in field: name, format = field.split(":", 1) else: name = field # This *should* be more flexible, but parsing complicated structures # out of the string is hard (and not necessarily useful) ... and I'm # being lazy. So for now `identifier` is "anything starting with a # letter" and digit args don't get attribute or element stuff. if name and name[0].isalpha(): if name in self._name_to_group_map: if self._name_types[name] != format: raise RepeatedNameError( 'field type %r for field "%s" ' "does not match previous seen type %r" % (format, name, self._name_types[name]) ) group = self._name_to_group_map[name] # match previously-seen value return r"(?P=%s)" % group else: group = self._to_group_name(name) self._name_types[name] = format self._named_fields.append(group) # this will become a group, which must not contain dots wrap = r"(?P<%s>%%s)" % group else: self._fixed_fields.append(self._group_index) wrap = r"(%s)" group = self._group_index # simplest case: no type specifier ({} or {name}) if not format: self._group_index += 1 return wrap % r".+?" # decode the format specification format = extract_format(format, self._extra_types) # figure type conversions, if any type = format["type"] is_numeric = type and type in "n%fegdobx" conv = self._type_conversions if type in self._extra_types: type_converter = self._extra_types[type] s = getattr(type_converter, "pattern", r".+?") regex_group_count = getattr(type_converter, "regex_group_count", 0) if regex_group_count is None: regex_group_count = 0 self._group_index += regex_group_count conv[group] = convert_first(type_converter) elif type == "n": s = r"\d{1,3}([,.]\d{3})*" self._group_index += 1 conv[group] = int_convert(10) elif type == "b": s = r"(0[bB])?[01]+" conv[group] = int_convert(2) self._group_index += 1 elif type == "o": s = r"(0[oO])?[0-7]+" conv[group] = int_convert(8) self._group_index += 1 elif type == "x": s = r"(0[xX])?[0-9a-fA-F]+" conv[group] = int_convert(16) self._group_index += 1 elif type == "%": s = r"\d+(\.\d+)?%" self._group_index += 1 conv[group] = percentage elif type == "f": s = r"\d*\.\d+" conv[group] = convert_first(float) elif type == "F": s = r"\d*\.\d+" conv[group] = convert_first(Decimal) elif type == "e": s = r"\d*\.\d+[eE][-+]?\d+|nan|NAN|[-+]?inf|[-+]?INF" conv[group] = convert_first(float) elif type == "g": s = r"\d+(\.\d+)?([eE][-+]?\d+)?|nan|NAN|[-+]?inf|[-+]?INF" self._group_index += 2 conv[group] = convert_first(float) elif type == "d": if format.get("width"): width = r"{1,%s}" % int(format["width"]) else: width = "+" s = r"\d{w}|[-+ ]?0[xX][0-9a-fA-F]{w}|[-+ ]?0[bB][01]{w}|[-+ ]?0[oO][0-7]{w}".format( w=width ) conv[group] = int_convert() # do not specify number base, determine it automatically elif any(k in type for k in dt_format_to_regex): s = get_regex_for_datetime_format(type) conv[group] = partial(strf_date_convert, type=type) elif type == "ti": s = r"(\d{4}-\d\d-\d\d)((\s+|T)%s)?(Z|\s*[-+]\d\d:?\d\d)?" % TIME_PAT n = self._group_index conv[group] = partial(date_convert, ymd=n + 1, hms=n + 4, tz=n + 7) self._group_index += 7 elif type == "tg": s = r"(\d{1,2}[-/](\d{1,2}|%s)[-/]\d{4})(\s+%s)?%s?%s?" s %= (ALL_MONTHS_PAT, TIME_PAT, AM_PAT, TZ_PAT) n = self._group_index conv[group] = partial( date_convert, dmy=n + 1, hms=n + 5, am=n + 8, tz=n + 9 ) self._group_index += 9 elif type == "ta": s = r"((\d{1,2}|%s)[-/]\d{1,2}[-/]\d{4})(\s+%s)?%s?%s?" s %= (ALL_MONTHS_PAT, TIME_PAT, AM_PAT, TZ_PAT) n = self._group_index conv[group] = partial( date_convert, mdy=n + 1, hms=n + 5, am=n + 8, tz=n + 9 ) self._group_index += 9 elif type == "te": # this will allow microseconds through if they're present, but meh s = r"(%s,\s+)?(\d{1,2}\s+%s\s+\d{4})\s+%s%s" s %= (DAYS_PAT, MONTHS_PAT, TIME_PAT, TZ_PAT) n = self._group_index conv[group] = partial(date_convert, dmy=n + 3, hms=n + 5, tz=n + 8) self._group_index += 8 elif type == "th": # slight flexibility here from the stock Apache format s = r"(\d{1,2}[-/]%s[-/]\d{4}):%s%s" % (MONTHS_PAT, TIME_PAT, TZ_PAT) n = self._group_index conv[group] = partial(date_convert, dmy=n + 1, hms=n + 3, tz=n + 6) self._group_index += 6 elif type == "tc": s = r"(%s)\s+%s\s+(\d{1,2})\s+%s\s+(\d{4})" s %= (DAYS_PAT, MONTHS_PAT, TIME_PAT) n = self._group_index conv[group] = partial(date_convert, d_m_y=(n + 4, n + 3, n + 8), hms=n + 5) self._group_index += 8 elif type == "tt": s = r"%s?%s?%s?" % (TIME_PAT, AM_PAT, TZ_PAT) n = self._group_index conv[group] = partial(date_convert, hms=n + 1, am=n + 4, tz=n + 5) self._group_index += 5 elif type == "ts": s = r"%s(\s+)(\d+)(\s+)(\d{1,2}:\d{1,2}:\d{1,2})?" % MONTHS_PAT n = self._group_index conv[group] = partial(date_convert, mm=n + 1, dd=n + 3, hms=n + 5) self._group_index += 5 elif type == "l": s = r"[A-Za-z]+" elif type: s = r"\%s+" % type elif format.get("precision"): if format.get("width"): s = r".{%s,%s}?" % (format["width"], format["precision"]) else: s = r".{1,%s}?" % format["precision"] elif format.get("width"): s = r".{%s,}?" % format["width"] else: s = r".+?" align = format["align"] fill = format["fill"] # handle some numeric-specific things like fill and sign if is_numeric: # prefix with something (align "=" trumps zero) if align == "=": # special case - align "=" acts like the zero above but with # configurable fill defaulting to "0" if not fill: fill = "0" s = r"%s*" % fill + s # allow numbers to be prefixed with a sign s = r"[-+ ]?" + s if not fill: fill = " " # Place into a group now - this captures the value we want to keep. # Everything else from now is just padding to be stripped off if wrap: s = wrap % s self._group_index += 1 if format["width"]: # all we really care about is that if the format originally # specified a width then there will probably be padding - without # an explicit alignment that'll mean right alignment with spaces # padding if not align: align = ">" if fill in r".\+?*[](){}^$": fill = "\\" + fill # align "=" has been handled if align == "<": s = "%s%s*" % (s, fill) elif align == ">": s = "%s*%s" % (fill, s) elif align == "^": s = "%s*%s%s*" % (fill, s, fill) return s class Result(object): """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`. """ def __init__(self, fixed, named, spans): self.fixed = fixed self.named = named self.spans = spans def __getitem__(self, item): if isinstance(item, (int, slice)): return self.fixed[item] return self.named[item] def __repr__(self): return "<%s %r %r>" % (self.__class__.__name__, self.fixed, self.named) def __contains__(self, name): return name in self.named class Match(object): """The 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. """ def __init__(self, parser, match): self.parser = parser self.match = match def evaluate_result(self): """Generate results for this Match""" return self.parser.evaluate_result(self.match) class ResultIterator(object): """The result of a findall() operation. Each element is a Result instance. """ def __init__(self, parser, string, pos, endpos, evaluate_result=True): self.parser = parser self.string = string self.pos = pos self.endpos = endpos self.evaluate_result = evaluate_result def __iter__(self): return self def __next__(self): m = self.parser._search_re.search(self.string, self.pos, self.endpos) if m is None: raise StopIteration() self.pos = m.end() if self.evaluate_result: return self.parser.evaluate_result(m) else: return Match(self.parser, m) # pre-py3k compat next = __next__ def parse(format, string, extra_types=None, evaluate_result=True, case_sensitive=False): """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. """ p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive) return p.parse(string, evaluate_result=evaluate_result) def search( format, string, pos=0, endpos=None, extra_types=None, evaluate_result=True, case_sensitive=False, ): """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. """ p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive) return p.search(string, pos, endpos, evaluate_result=evaluate_result) def findall( format, string, pos=0, endpos=None, extra_types=None, evaluate_result=True, case_sensitive=False, ): """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". """ p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive) return p.findall(string, pos, endpos, evaluate_result=evaluate_result) def compile(format, extra_types=None, case_sensitive=False): """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. """ return Parser(format, extra_types=extra_types, case_sensitive=case_sensitive) # Copyright (c) 2012-2020 Richard Jones # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # vim: set filetype=python ts=4 sw=4 et si tw=75 r1chardj0n3s-parse-334db14/pyproject.toml000066400000000000000000000016201463175247200203000ustar00rootroot00000000000000[build-system] requires = ["setuptools>=61.2"] build-backend = "setuptools.build_meta" [project] name = "parse" dynamic = ["version"] readme = "README.rst" description = "parse() is the opposite of format()" license = {file = "LICENSE"} classifiers = [ "Environment :: Web Environment", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "Topic :: Software Development :: Code Generators", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: MIT License", ] [[project.authors]] name = "Richard Jones" email = "richard@python.org" [[project.maintainers]] name = "Wim Glenn" email = "hey@wimglenn.com" [project.urls] homepage = "https://github.com/r1chardj0n3s/parse" [tool.setuptools] py-modules = ["parse"] [tool.setuptools.dynamic] version = {attr = "parse.__version__"} [tool.distutils.bdist_wheel] universal = true r1chardj0n3s-parse-334db14/tests/000077500000000000000000000000001463175247200165275ustar00rootroot00000000000000r1chardj0n3s-parse-334db14/tests/requirements.txt000066400000000000000000000000221463175247200220050ustar00rootroot00000000000000pytest pytest-cov r1chardj0n3s-parse-334db14/tests/test_bugs.py000066400000000000000000000057751463175247200211160ustar00rootroot00000000000000import pickle from datetime import datetime import parse def test_tz_compare_to_None(): utc = parse.FixedTzOffset(0, "UTC") assert utc is not None assert utc != "spam" def test_named_date_issue7(): r = parse.parse("on {date:ti}", "on 2012-09-17") assert r["date"] == datetime(2012, 9, 17, 0, 0, 0) # fix introduced regressions r = parse.parse("a {:ti} b", "a 1997-07-16T19:20 b") assert r[0] == datetime(1997, 7, 16, 19, 20, 0) r = parse.parse("a {:ti} b", "a 1997-07-16T19:20Z b") utc = parse.FixedTzOffset(0, "UTC") assert r[0] == datetime(1997, 7, 16, 19, 20, tzinfo=utc) r = parse.parse("a {date:ti} b", "a 1997-07-16T19:20Z b") assert r["date"] == datetime(1997, 7, 16, 19, 20, tzinfo=utc) def test_dotted_type_conversion_pull_8(): # test pull request 8 which fixes type conversion related to dotted # names being applied correctly r = parse.parse("{a.b:d}", "1") assert r["a.b"] == 1 r = parse.parse("{a_b:w} {a.b:d}", "1 2") assert r["a_b"] == "1" assert r["a.b"] == 2 def test_pm_overflow_issue16(): r = parse.parse("Meet at {:tg}", "Meet at 1/2/2011 12:45 PM") assert r[0] == datetime(2011, 2, 1, 12, 45) def test_pm_handling_issue57(): r = parse.parse("Meet at {:tg}", "Meet at 1/2/2011 12:15 PM") assert r[0] == datetime(2011, 2, 1, 12, 15) r = parse.parse("Meet at {:tg}", "Meet at 1/2/2011 12:15 AM") assert r[0] == datetime(2011, 2, 1, 0, 15) def test_user_type_with_group_count_issue60(): @parse.with_pattern(r"((\w+))", regex_group_count=2) def parse_word_and_covert_to_uppercase(text): return text.strip().upper() @parse.with_pattern(r"\d+") def parse_number(text): return int(text) # -- CASE: Use named (OK) type_map = {"Name": parse_word_and_covert_to_uppercase, "Number": parse_number} r = parse.parse( "Hello {name:Name} {number:Number}", "Hello Alice 42", extra_types=type_map ) assert r.named == {"name": "ALICE", "number": 42} # -- CASE: Use unnamed/fixed (problematic) r = parse.parse("Hello {:Name} {:Number}", "Hello Alice 42", extra_types=type_map) assert r[0] == "ALICE" assert r[1] == 42 def test_unmatched_brace_doesnt_match(): r = parse.parse("{who.txt", "hello") assert r is None def test_pickling_bug_110(): p = parse.compile("{a:d}") # prior to the fix, this would raise an AttributeError pickle.dumps(p) def test_unused_centered_alignment_bug(): r = parse.parse("{:^2S}", "foo") assert r[0] == "foo" r = parse.search("{:^2S}", "foo") assert r[0] == "foo" # specifically test for the case in issue #118 as well r = parse.parse("Column {:d}:{:^}", "Column 1: Timestep") assert r[0] == 1 assert r[1] == "Timestep" def test_unused_left_alignment_bug(): r = parse.parse("{:<2S}", "foo") assert r[0] == "foo" r = parse.search("{:<2S}", "foo") assert r[0] == "foo" def test_match_trailing_newline(): r = parse.parse("{}", "test\n") assert r[0] == "test\n" r1chardj0n3s-parse-334db14/tests/test_findall.py000066400000000000000000000011761463175247200215560ustar00rootroot00000000000000import parse def test_findall(): s = "".join( r.fixed[0] for r in parse.findall(">{}<", "

some bold text

") ) assert s == "some bold text" def test_no_evaluate_result(): s = "".join( m.evaluate_result().fixed[0] for m in parse.findall( ">{}<", "

some bold text

", evaluate_result=False ) ) assert s == "some bold text" def test_case_sensitivity(): l = [r.fixed[0] for r in parse.findall("x({})x", "X(hi)X")] assert l == ["hi"] l = [r.fixed[0] for r in parse.findall("x({})x", "X(hi)X", case_sensitive=True)] assert l == [] r1chardj0n3s-parse-334db14/tests/test_parse.py000066400000000000000000000614001463175247200212530ustar00rootroot00000000000000# coding: utf-8 import sys from datetime import date from datetime import datetime from datetime import time import pytest import parse def test_no_match(): # string does not match format assert parse.parse("{{hello}}", "hello") is None def test_nothing(): # do no actual parsing r = parse.parse("{{hello}}", "{hello}") assert r.fixed == () assert r.named == {} def test_no_evaluate_result(): # pull a fixed value out of string match = parse.parse("hello {}", "hello world", evaluate_result=False) r = match.evaluate_result() assert r.fixed == ("world",) def test_regular_expression(): # match an actual regular expression s = r"^(hello\s[wW]{}!+.*)$" e = s.replace("{}", "orld") r = parse.parse(s, e) assert r.fixed == ("orld",) e = s.replace("{}", ".*?") r = parse.parse(s, e) assert r.fixed == (".*?",) def test_question_mark(): # issue9: make sure a ? in the parse string is handled correctly r = parse.parse('"{}"?', '"teststr"?') assert r[0] == "teststr" def test_pipe(): # issue22: make sure a | in the parse string is handled correctly r = parse.parse("| {}", "| teststr") assert r[0] == "teststr" def test_unicode(): # issue29: make sure unicode is parsable r = parse.parse("{}", "t€ststr") assert r[0] == "t€ststr" def test_hexadecimal(): # issue42: make sure bare hexadecimal isn't matched as "digits" r = parse.parse("{:d}", "abcdef") assert r is None def test_fixed(): # pull a fixed value out of string r = parse.parse("hello {}", "hello world") assert r.fixed == ("world",) def test_left(): # pull left-aligned text out of string r = parse.parse("{:<} world", "hello world") assert r.fixed == ("hello",) def test_right(): # pull right-aligned text out of string r = parse.parse("hello {:>}", "hello world") assert r.fixed == ("world",) def test_center(): # pull center-aligned text out of string r = parse.parse("hello {:^} world", "hello there world") assert r.fixed == ("there",) def test_typed(): # pull a named, typed values out of string r = parse.parse("hello {:d} {:w}", "hello 12 people") assert r.fixed == (12, "people") r = parse.parse("hello {:w} {:w}", "hello 12 people") assert r.fixed == ("12", "people") def test_sign(): # sign is ignored r = parse.parse("Pi = {:.7f}", "Pi = 3.1415926") assert r.fixed == (3.1415926,) r = parse.parse("Pi = {:+.7f}", "Pi = 3.1415926") assert r.fixed == (3.1415926,) r = parse.parse("Pi = {:-.7f}", "Pi = 3.1415926") assert r.fixed == (3.1415926,) r = parse.parse("Pi = {: .7f}", "Pi = 3.1415926") assert r.fixed == (3.1415926,) def test_precision(): # pull a float out of a string r = parse.parse("Pi = {:.7f}", "Pi = 3.1415926") assert r.fixed == (3.1415926,) r = parse.parse("Pi/10 = {:8.5f}", "Pi/10 = 0.31415") assert r.fixed == (0.31415,) # float may have not leading zero r = parse.parse("Pi/10 = {:8.5f}", "Pi/10 = .31415") assert r.fixed == (0.31415,) r = parse.parse("Pi/10 = {:8.5f}", "Pi/10 = -.31415") assert r.fixed == (-0.31415,) def test_custom_type(): # use a custom type r = parse.parse( "{:shouty} {:spam}", "hello world", {"shouty": lambda s: s.upper(), "spam": lambda s: "".join(reversed(s))}, ) assert r.fixed == ("HELLO", "dlrow") r = parse.parse("{:d}", "12", {"d": lambda s: int(s) * 2}) assert r.fixed == (24,) r = parse.parse("{:d}", "12") assert r.fixed == (12,) def test_typed_fail(): # pull a named, typed values out of string assert parse.parse("hello {:d} {:w}", "hello people 12") is None def test_named(): # pull a named value out of string r = parse.parse("hello {name}", "hello world") assert r.named == {"name": "world"} def test_named_repeated(): # test a name may be repeated r = parse.parse("{n} {n}", "x x") assert r.named == {"n": "x"} def test_named_repeated_type(): # test a name may be repeated with type conversion r = parse.parse("{n:d} {n:d}", "1 1") assert r.named == {"n": 1} def test_named_repeated_fail_value(): # test repeated name fails if value mismatches r = parse.parse("{n} {n}", "x y") assert r is None def test_named_repeated_type_fail_value(): # test repeated name with type conversion fails if value mismatches r = parse.parse("{n:d} {n:d}", "1 2") assert r is None def test_named_repeated_type_mismatch(): # test repeated name with mismatched type with pytest.raises(parse.RepeatedNameError): parse.compile("{n:d} {n:w}") def test_mixed(): # pull a fixed and named values out of string r = parse.parse("hello {} {name} {} {spam}", "hello world and other beings") assert r.fixed == ("world", "other") assert r.named == {"name": "and", "spam": "beings"} def test_named_typed(): # pull a named, typed values out of string r = parse.parse("hello {number:d} {things}", "hello 12 people") assert r.named == {"number": 12, "things": "people"} r = parse.parse("hello {number:w} {things}", "hello 12 people") assert r.named == {"number": "12", "things": "people"} def test_named_aligned_typed(): # pull a named, typed values out of string r = parse.parse("hello {number:d} {things}", "hello 12 people") assert r.named == {"number": 12, "things": "people"} r = parse.parse("hello {number:^d} {things}", "hello 12 people") assert r.named == {"number": 12, "things": "people"} def test_multiline(): r = parse.parse("hello\n{}\nworld", "hello\nthere\nworld") assert r.fixed[0] == "there" def test_spans(): # test the string sections our fields come from string = "hello world" r = parse.parse("hello {}", string) assert r.spans == {0: (6, 11)} start, end = r.spans[0] assert string[start:end] == r.fixed[0] string = "hello world" r = parse.parse("hello {:>}", string) assert r.spans == {0: (10, 15)} start, end = r.spans[0] assert string[start:end] == r.fixed[0] string = "hello 0x12 world" r = parse.parse("hello {val:x} world", string) assert r.spans == {"val": (6, 10)} start, end = r.spans["val"] assert string[start:end] == "0x%x" % r.named["val"] string = "hello world and other beings" r = parse.parse("hello {} {name} {} {spam}", string) assert r.spans == {0: (6, 11), "name": (12, 15), 1: (16, 21), "spam": (22, 28)} def test_numbers(): # pull a numbers out of a string def y(fmt, s, e, str_equals=False): p = parse.compile(fmt) r = p.parse(s) assert r is not None r = r.fixed[0] if str_equals: assert str(r) == str(e) else: assert r == e def n(fmt, s, e): assert parse.parse(fmt, s) is None y("a {:d} b", "a 0 b", 0) y("a {:d} b", "a 12 b", 12) y("a {:5d} b", "a 12 b", 12) y("a {:5d} b", "a -12 b", -12) y("a {:d} b", "a -12 b", -12) y("a {:d} b", "a +12 b", 12) y("a {:d} b", "a 12 b", 12) y("a {:d} b", "a 0b1000 b", 8) y("a {:d} b", "a 0o1000 b", 512) y("a {:d} b", "a 0x1000 b", 4096) y("a {:d} b", "a 0xabcdef b", 0xABCDEF) y("a {:%} b", "a 100% b", 1) y("a {:%} b", "a 50% b", 0.5) y("a {:%} b", "a 50.1% b", 0.501) y("a {:n} b", "a 100 b", 100) y("a {:n} b", "a 1,000 b", 1000) y("a {:n} b", "a 1.000 b", 1000) y("a {:n} b", "a -1,000 b", -1000) y("a {:n} b", "a 10,000 b", 10000) y("a {:n} b", "a 100,000 b", 100000) n("a {:n} b", "a 100,00 b", None) y("a {:n} b", "a 100.000 b", 100000) y("a {:n} b", "a 1.000.000 b", 1000000) y("a {:f} b", "a 12.0 b", 12.0) y("a {:f} b", "a -12.1 b", -12.1) y("a {:f} b", "a +12.1 b", 12.1) y("a {:f} b", "a .121 b", 0.121) y("a {:f} b", "a -.121 b", -0.121) n("a {:f} b", "a 12 b", None) y("a {:e} b", "a 1.0e10 b", 1.0e10) y("a {:e} b", "a .0e10 b", 0.0e10) y("a {:e} b", "a 1.0E10 b", 1.0e10) y("a {:e} b", "a 1.10000e10 b", 1.1e10) y("a {:e} b", "a 1.0e-10 b", 1.0e-10) y("a {:e} b", "a 1.0e+10 b", 1.0e10) # can't actually test this one on values 'cos nan != nan y("a {:e} b", "a nan b", float("nan"), str_equals=True) y("a {:e} b", "a NAN b", float("nan"), str_equals=True) y("a {:e} b", "a inf b", float("inf")) y("a {:e} b", "a +inf b", float("inf")) y("a {:e} b", "a -inf b", float("-inf")) y("a {:e} b", "a INF b", float("inf")) y("a {:e} b", "a +INF b", float("inf")) y("a {:e} b", "a -INF b", float("-inf")) y("a {:g} b", "a 1 b", 1) y("a {:g} b", "a 1e10 b", 1e10) y("a {:g} b", "a 1.0e10 b", 1.0e10) y("a {:g} b", "a 1.0E10 b", 1.0e10) y("a {:b} b", "a 1000 b", 8) y("a {:b} b", "a 0b1000 b", 8) y("a {:o} b", "a 12345670 b", int("12345670", 8)) y("a {:o} b", "a 0o12345670 b", int("12345670", 8)) y("a {:x} b", "a 1234567890abcdef b", 0x1234567890ABCDEF) y("a {:x} b", "a 1234567890ABCDEF b", 0x1234567890ABCDEF) y("a {:x} b", "a 0x1234567890abcdef b", 0x1234567890ABCDEF) y("a {:x} b", "a 0x1234567890ABCDEF b", 0x1234567890ABCDEF) y("a {:05d} b", "a 00001 b", 1) y("a {:05d} b", "a -00001 b", -1) y("a {:05d} b", "a +00001 b", 1) y("a {:02d} b", "a 10 b", 10) y("a {:=d} b", "a 000012 b", 12) y("a {:x=5d} b", "a xxx12 b", 12) y("a {:x=5d} b", "a -xxx12 b", -12) # Test that hex numbers that ambiguously start with 0b / 0B are parsed correctly # See issue #65 (https://github.com/r1chardj0n3s/parse/issues/65) y("a {:x} b", "a 0B b", 0xB) y("a {:x} b", "a 0B1 b", 0xB1) y("a {:x} b", "a 0b b", 0xB) y("a {:x} b", "a 0b1 b", 0xB1) # Test that number signs are understood correctly y("a {:d} b", "a -0o10 b", -8) y("a {:d} b", "a -0b1010 b", -10) y("a {:d} b", "a -0x1010 b", -0x1010) y("a {:o} b", "a -10 b", -8) y("a {:b} b", "a -1010 b", -10) y("a {:x} b", "a -1010 b", -0x1010) y("a {:d} b", "a +0o10 b", 8) y("a {:d} b", "a +0b1010 b", 10) y("a {:d} b", "a +0x1010 b", 0x1010) y("a {:o} b", "a +10 b", 8) y("a {:b} b", "a +1010 b", 10) y("a {:x} b", "a +1010 b", 0x1010) def test_two_datetimes(): r = parse.parse("a {:ti} {:ti} b", "a 1997-07-16 2012-08-01 b") assert len(r.fixed) == 2 assert r[0] == datetime(1997, 7, 16) assert r[1] == datetime(2012, 8, 1) def test_flexible_datetimes(): r = parse.parse("a {:%Y-%m-%d} b", "a 1997-07-16 b") assert len(r.fixed) == 1 assert r[0] == date(1997, 7, 16) r = parse.parse("a {:%Y-%b-%d} b", "a 1997-Feb-16 b") assert len(r.fixed) == 1 assert r[0] == date(1997, 2, 16) r = parse.parse("a {:%Y-%b-%d} {:d} b", "a 1997-Feb-16 8 b") assert len(r.fixed) == 2 assert r[0] == date(1997, 2, 16) r = parse.parse("a {my_date:%Y-%b-%d} {num:d} b", "a 1997-Feb-16 8 b") assert (r.named["my_date"]) == date(1997, 2, 16) assert (r.named["num"]) == 8 r = parse.parse("a {:%Y-%B-%d} b", "a 1997-February-16 b") assert r[0] == date(1997, 2, 16) r = parse.parse("a {:%Y%m%d} b", "a 19970716 b") assert r[0] == date(1997, 7, 16) def test_flexible_datetime_with_colon(): r = parse.parse("{dt:%Y-%m-%d %H:%M:%S}", "2023-11-21 13:23:27") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27) def test_datetime_with_various_subsecond_precision(): r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.123456") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123456) r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.12345") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123450) r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.1234") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123400) r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.123") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123000) r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.0") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 0) @pytest.mark.skipif( sys.version_info[0] < 3, reason="Python 3+ required for timezone support" ) def test_flexible_datetime_with_timezone(): from datetime import timezone r = parse.parse("{dt:%Y-%m-%d %H:%M:%S %z}", "2023-11-21 13:23:27 +0000") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, tzinfo=timezone.utc) @pytest.mark.skipif( sys.version_info[0] < 3, reason="Python 3+ required for timezone support" ) def test_flexible_datetime_with_timezone_that_has_colons(): from datetime import timezone r = parse.parse("{dt:%Y-%m-%d %H:%M:%S %z}", "2023-11-21 13:23:27 +00:00:00") assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, tzinfo=timezone.utc) def test_flexible_time(): r = parse.parse("a {time:%H:%M:%S} b", "a 13:23:27 b") assert r.named["time"] == time(13, 23, 27) def test_flexible_time_no_hour(): r = parse.parse("a {time:%M:%S} b", "a 23:27 b") assert r.named["time"] == time(0, 23, 27) def test_flexible_time_ms(): r = parse.parse("a {time:%M:%S:%f} b", "a 23:27:123456 b") assert r.named["time"] == time(0, 23, 27, 123456) def test_flexible_dates_single_digit(): r = parse.parse("{dt:%Y/%m/%d}", "2023/1/1") assert r.named["dt"] == date(2023, 1, 1) def test_flexible_dates_j(): r = parse.parse("{dt:%Y/%j}", "2023/9") assert r.named["dt"] == date(2023, 1, 9) r = parse.parse("{dt:%Y/%j}", "2023/009") assert r.named["dt"] == date(2023, 1, 9) def test_flexible_dates_year_current_year_inferred(): r = parse.parse("{dt:%j}", "9") assert r.named["dt"] == date(datetime.today().year, 1, 9) def test_datetimes(): def y(fmt, s, e, tz=None): p = parse.compile(fmt) r = p.parse(s) assert r is not None r = r.fixed[0] assert r == e assert tz is None or r.tzinfo == tz utc = parse.FixedTzOffset(0, "UTC") assert repr(utc) == "" aest = parse.FixedTzOffset(10 * 60, "+1000") tz60 = parse.FixedTzOffset(60, "+01:00") # ISO 8660 variants # YYYY-MM-DD (eg 1997-07-16) y("a {:ti} b", "a 1997-07-16 b", datetime(1997, 7, 16)) # YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) y("a {:ti} b", "a 1997-07-16 19:20 b", datetime(1997, 7, 16, 19, 20, 0)) y("a {:ti} b", "a 1997-07-16T19:20 b", datetime(1997, 7, 16, 19, 20, 0)) y( "a {:ti} b", "a 1997-07-16T19:20Z b", datetime(1997, 7, 16, 19, 20, tzinfo=utc), ) y( "a {:ti} b", "a 1997-07-16T19:20+0100 b", datetime(1997, 7, 16, 19, 20, tzinfo=tz60), ) y( "a {:ti} b", "a 1997-07-16T19:20+01:00 b", datetime(1997, 7, 16, 19, 20, tzinfo=tz60), ) y( "a {:ti} b", "a 1997-07-16T19:20 +01:00 b", datetime(1997, 7, 16, 19, 20, tzinfo=tz60), ) # YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00) y("a {:ti} b", "a 1997-07-16 19:20:30 b", datetime(1997, 7, 16, 19, 20, 30)) y("a {:ti} b", "a 1997-07-16T19:20:30 b", datetime(1997, 7, 16, 19, 20, 30)) y( "a {:ti} b", "a 1997-07-16T19:20:30Z b", datetime(1997, 7, 16, 19, 20, 30, tzinfo=utc), ) y( "a {:ti} b", "a 1997-07-16T19:20:30+01:00 b", datetime(1997, 7, 16, 19, 20, 30, tzinfo=tz60), ) y( "a {:ti} b", "a 1997-07-16T19:20:30 +01:00 b", datetime(1997, 7, 16, 19, 20, 30, tzinfo=tz60), ) # YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) y( "a {:ti} b", "a 1997-07-16 19:20:30.500000 b", datetime(1997, 7, 16, 19, 20, 30, 500000), ) y( "a {:ti} b", "a 1997-07-16T19:20:30.500000 b", datetime(1997, 7, 16, 19, 20, 30, 500000), ) y( "a {:ti} b", "a 1997-07-16T19:20:30.5Z b", datetime(1997, 7, 16, 19, 20, 30, 500000, tzinfo=utc), ) y( "a {:ti} b", "a 1997-07-16T19:20:30.5+01:00 b", datetime(1997, 7, 16, 19, 20, 30, 500000, tzinfo=tz60), ) aest_d = datetime(2011, 11, 21, 10, 21, 36, tzinfo=aest) dt = datetime(2011, 11, 21, 10, 21, 36) dt00 = datetime(2011, 11, 21, 10, 21) d = datetime(2011, 11, 21) # te RFC2822 e-mail format datetime y("a {:te} b", "a Mon, 21 Nov 2011 10:21:36 +1000 b", aest_d) y("a {:te} b", "a Mon, 21 Nov 2011 10:21:36 +10:00 b", aest_d) y("a {:te} b", "a 21 Nov 2011 10:21:36 +1000 b", aest_d) # tg global (day/month) format datetime y("a {:tg} b", "a 21/11/2011 10:21:36 AM +1000 b", aest_d) y("a {:tg} b", "a 21/11/2011 10:21:36 AM +10:00 b", aest_d) y("a {:tg} b", "a 21-11-2011 10:21:36 AM +1000 b", aest_d) y("a {:tg} b", "a 21/11/2011 10:21:36 +1000 b", aest_d) y("a {:tg} b", "a 21/11/2011 10:21:36 b", dt) y("a {:tg} b", "a 21/11/2011 10:21 b", dt00) y("a {:tg} b", "a 21-11-2011 b", d) y("a {:tg} b", "a 21-Nov-2011 10:21:36 AM +1000 b", aest_d) y("a {:tg} b", "a 21-November-2011 10:21:36 AM +1000 b", aest_d) # ta US (month/day) format datetime y("a {:ta} b", "a 11/21/2011 10:21:36 AM +1000 b", aest_d) y("a {:ta} b", "a 11/21/2011 10:21:36 AM +10:00 b", aest_d) y("a {:ta} b", "a 11-21-2011 10:21:36 AM +1000 b", aest_d) y("a {:ta} b", "a 11/21/2011 10:21:36 +1000 b", aest_d) y("a {:ta} b", "a 11/21/2011 10:21:36 b", dt) y("a {:ta} b", "a 11/21/2011 10:21 b", dt00) y("a {:ta} b", "a 11-21-2011 b", d) y("a {:ta} b", "a Nov-21-2011 10:21:36 AM +1000 b", aest_d) y("a {:ta} b", "a November-21-2011 10:21:36 AM +1000 b", aest_d) y("a {:ta} b", "a November-21-2011 b", d) # ts Linux System log format datetime y( "a {:ts} b", "a Nov 21 10:21:36 b", datetime(datetime.today().year, 11, 21, 10, 21, 36), ) y( "a {:ts} b", "a Nov 1 10:21:36 b", datetime(datetime.today().year, 11, 1, 10, 21, 36), ) y( "a {:ts} b", "a Nov 1 03:21:36 b", datetime(datetime.today().year, 11, 1, 3, 21, 36), ) # th HTTP log format date/time datetime y("a {:th} b", "a 21/Nov/2011:10:21:36 +1000 b", aest_d) y("a {:th} b", "a 21/Nov/2011:10:21:36 +10:00 b", aest_d) d = datetime(2011, 11, 21, 10, 21, 36) # tc ctime() format datetime y("a {:tc} b", "a Mon Nov 21 10:21:36 2011 b", d) t530 = parse.FixedTzOffset(-5 * 60 - 30, "-5:30") t830 = parse.FixedTzOffset(-8 * 60 - 30, "-8:30") # tt Time time y("a {:tt} b", "a 10:21:36 AM +1000 b", time(10, 21, 36, tzinfo=aest)) y("a {:tt} b", "a 10:21:36 AM +10:00 b", time(10, 21, 36, tzinfo=aest)) y("a {:tt} b", "a 10:21:36 AM b", time(10, 21, 36)) y("a {:tt} b", "a 10:21:36 PM b", time(22, 21, 36)) y("a {:tt} b", "a 10:21:36 b", time(10, 21, 36)) y("a {:tt} b", "a 10:21 b", time(10, 21)) y("a {:tt} b", "a 10:21:36 PM -5:30 b", time(22, 21, 36, tzinfo=t530)) y("a {:tt} b", "a 10:21:36 PM -530 b", time(22, 21, 36, tzinfo=t530)) y("a {:tt} b", "a 10:21:36 PM -05:30 b", time(22, 21, 36, tzinfo=t530)) y("a {:tt} b", "a 10:21:36 PM -0530 b", time(22, 21, 36, tzinfo=t530)) y("a {:tt} b", "a 10:21:36 PM -08:30 b", time(22, 21, 36, tzinfo=t830)) y("a {:tt} b", "a 10:21:36 PM -0830 b", time(22, 21, 36, tzinfo=t830)) def test_datetime_group_count(): # test we increment the group count correctly for datetimes r = parse.parse("{:ti} {}", "1972-01-01 spam") assert r.fixed[1] == "spam" r = parse.parse("{:tg} {}", "1-1-1972 spam") assert r.fixed[1] == "spam" r = parse.parse("{:ta} {}", "1-1-1972 spam") assert r.fixed[1] == "spam" r = parse.parse("{:th} {}", "21/Nov/2011:10:21:36 +1000 spam") assert r.fixed[1] == "spam" r = parse.parse("{:te} {}", "21 Nov 2011 10:21:36 +1000 spam") assert r.fixed[1] == "spam" r = parse.parse("{:tc} {}", "Mon Nov 21 10:21:36 2011 spam") assert r.fixed[1] == "spam" r = parse.parse("{:tt} {}", "10:21 spam") assert r.fixed[1] == "spam" def test_mixed_types(): # stress-test: pull one of everything out of a string r = parse.parse( """ letters: {:w} non-letters: {:W} whitespace: "{:s}" non-whitespace: \t{:S}\n digits: {:d} {:d} non-digits: {:D} numbers with thousands: {:n} fixed-point: {:f} floating-point: {:e} general numbers: {:g} {:g} binary: {:b} octal: {:o} hex: {:x} ISO 8601 e.g. {:ti} RFC2822 e.g. {:te} Global e.g. {:tg} US e.g. {:ta} ctime() e.g. {:tc} HTTP e.g. {:th} time: {:tt} final value: {} """, """ letters: abcdef_GHIJLK non-letters: !@#%$ *^% whitespace: " \t\n" non-whitespace: \tabc\n digits: 12345 0b1011011 non-digits: abcdef numbers with thousands: 1,000 fixed-point: 100.2345 floating-point: 1.1e-10 general numbers: 1 1.1 binary: 0b1000 octal: 0o1000 hex: 0x1000 ISO 8601 e.g. 1972-01-20T10:21:36Z RFC2822 e.g. Mon, 20 Jan 1972 10:21:36 +1000 Global e.g. 20/1/1972 10:21:36 AM +1:00 US e.g. 1/20/1972 10:21:36 PM +10:30 ctime() e.g. Sun Sep 16 01:03:52 1973 HTTP e.g. 21/Nov/2011:00:07:11 +0000 time: 10:21:36 PM -5:30 final value: spam """, ) assert r is not None assert r.fixed[22] == "spam" def test_mixed_type_variant(): r = parse.parse( """ letters: {:w} non-letters: {:W} whitespace: "{:s}" non-whitespace: \t{:S}\n digits: {:d} non-digits: {:D} numbers with thousands: {:n} fixed-point: {:f} floating-point: {:e} general numbers: {:g} {:g} binary: {:b} octal: {:o} hex: {:x} ISO 8601 e.g. {:ti} RFC2822 e.g. {:te} Global e.g. {:tg} US e.g. {:ta} ctime() e.g. {:tc} HTTP e.g. {:th} time: {:tt} final value: {} """, """ letters: abcdef_GHIJLK non-letters: !@#%$ *^% whitespace: " \t\n" non-whitespace: \tabc\n digits: 0xabcdef non-digits: abcdef numbers with thousands: 1.000.000 fixed-point: 0.00001 floating-point: NAN general numbers: 1.1e10 nan binary: 0B1000 octal: 0O1000 hex: 0X1000 ISO 8601 e.g. 1972-01-20T10:21:36Z RFC2822 e.g. Mon, 20 Jan 1972 10:21:36 +1000 Global e.g. 20/1/1972 10:21:36 AM +1:00 US e.g. 1/20/1972 10:21:36 PM +10:30 ctime() e.g. Sun Sep 16 01:03:52 1973 HTTP e.g. 21/Nov/2011:00:07:11 +0000 time: 10:21:36 PM -5:30 final value: spam """, ) assert r is not None assert r.fixed[21] == "spam" @pytest.mark.skipif(sys.version_info >= (3, 5), reason="Python 3.5 removed the limit of 100 named groups in a regular expression") def test_too_many_fields(): # Python 3.5 removed the limit of 100 named groups in a regular expression, # so only test for the exception if the limit exists. p = parse.compile("{:ti}" * 15) with pytest.raises(parse.TooManyFields): p.parse("") def test_letters(): res = parse.parse("{:l}", "") assert res is None res = parse.parse("{:l}", "sPaM") assert res.fixed == ("sPaM",) res = parse.parse("{:l}", "sP4M") assert res is None res = parse.parse("{:l}", "sP_M") assert res is None def test_strftime_strptime_roundtrip(): dt = datetime.now() fmt = "_".join([k for k in parse.dt_format_to_regex if k != "%z"]) s = dt.strftime(fmt) [res] = parse.parse("{:" + fmt + "}", s) assert res == dt def test_parser_format(): parser = parse.compile("hello {}") assert parser.format.format("world") == "hello world" with pytest.raises(AttributeError): parser.format = "hi {}" def test_hyphen_inside_field_name(): # https://github.com/r1chardj0n3s/parse/issues/86 # https://github.com/python-openapi/openapi-core/issues/672 template = "/local/sub/{user-id}/duration" assert parse.Parser(template).named_fields == ["user_id"] string = "https://dummy_server.com/local/sub/1647222638/duration" result = parse.search(template, string) assert result["user-id"] == "1647222638" def test_hyphen_inside_field_name_collision_handling(): template = "/foo/{user-id}/{user_id}/{user.id}/bar/" assert parse.Parser(template).named_fields == ["user_id", "user__id", "user___id"] string = "/foo/1/2/3/bar/" result = parse.search(template, string) assert result["user-id"] == "1" assert result["user_id"] == "2" assert result["user.id"] == "3" r1chardj0n3s-parse-334db14/tests/test_parsetype.py000066400000000000000000000153411463175247200221600ustar00rootroot00000000000000from decimal import Decimal import pytest import parse def assert_match(parser, text, param_name, expected): result = parser.parse(text) assert result[param_name] == expected def assert_mismatch(parser, text, param_name): result = parser.parse(text) assert result is None def assert_fixed_match(parser, text, expected): result = parser.parse(text) assert result.fixed == expected def assert_fixed_mismatch(parser, text): result = parser.parse(text) assert result is None def test_pattern_should_be_used(): def parse_number(text): return int(text) parse_number.pattern = r"\d+" parse_number.name = "Number" # For testing only. extra_types = {parse_number.name: parse_number} format = "Value is {number:Number} and..." parser = parse.Parser(format, extra_types) assert_match(parser, "Value is 42 and...", "number", 42) assert_match(parser, "Value is 00123 and...", "number", 123) assert_mismatch(parser, "Value is ALICE and...", "number") assert_mismatch(parser, "Value is -123 and...", "number") def test_pattern_should_be_used2(): def parse_yesno(text): return parse_yesno.mapping[text.lower()] parse_yesno.mapping = { "yes": True, "no": False, "on": True, "off": False, "true": True, "false": False, } parse_yesno.pattern = r"|".join(parse_yesno.mapping.keys()) parse_yesno.name = "YesNo" # For testing only. extra_types = {parse_yesno.name: parse_yesno} format = "Answer: {answer:YesNo}" parser = parse.Parser(format, extra_types) # -- ENSURE: Known enum values are correctly extracted. for value_name, value in parse_yesno.mapping.items(): text = "Answer: %s" % value_name assert_match(parser, text, "answer", value) # -- IGNORE-CASE: In parsing, calls type converter function !!! assert_match(parser, "Answer: YES", "answer", True) assert_mismatch(parser, "Answer: __YES__", "answer") def test_with_pattern(): ab_vals = {"a": 1, "b": 2} @parse.with_pattern(r"[ab]") def ab(text): return ab_vals[text] parser = parse.Parser("test {result:ab}", {"ab": ab}) assert_match(parser, "test a", "result", 1) assert_match(parser, "test b", "result", 2) assert_mismatch(parser, "test c", "result") def test_with_pattern_and_regex_group_count(): # -- SPECIAL-CASE: Regex-grouping is used in user-defined type # NOTE: Missing or wroung regex_group_counts cause problems # with parsing following params. @parse.with_pattern(r"(meter|kilometer)", regex_group_count=1) def parse_unit(text): return text.strip() @parse.with_pattern(r"\d+") def parse_number(text): return int(text) type_converters = {"Number": parse_number, "Unit": parse_unit} # -- CASE: Unnamed-params (affected) parser = parse.Parser("test {:Unit}-{:Number}", type_converters) assert_fixed_match(parser, "test meter-10", ("meter", 10)) assert_fixed_match(parser, "test kilometer-20", ("kilometer", 20)) assert_fixed_mismatch(parser, "test liter-30") # -- CASE: Named-params (uncritical; should not be affected) # REASON: Named-params have additional, own grouping. parser2 = parse.Parser("test {unit:Unit}-{value:Number}", type_converters) assert_match(parser2, "test meter-10", "unit", "meter") assert_match(parser2, "test meter-10", "value", 10) assert_match(parser2, "test kilometer-20", "unit", "kilometer") assert_match(parser2, "test kilometer-20", "value", 20) assert_mismatch(parser2, "test liter-30", "unit") def test_with_pattern_and_wrong_regex_group_count_raises_error(): # -- SPECIAL-CASE: # Regex-grouping is used in user-defined type, but wrong value is provided. @parse.with_pattern(r"(meter|kilometer)", regex_group_count=1) def parse_unit(text): return text.strip() @parse.with_pattern(r"\d+") def parse_number(text): return int(text) # -- CASE: Unnamed-params (affected) BAD_REGEX_GROUP_COUNTS_AND_ERRORS = [ (None, ValueError), (0, ValueError), (2, IndexError), ] for bad_regex_group_count, error_class in BAD_REGEX_GROUP_COUNTS_AND_ERRORS: parse_unit.regex_group_count = bad_regex_group_count # -- OVERRIDE-HERE type_converters = {"Number": parse_number, "Unit": parse_unit} parser = parse.Parser("test {:Unit}-{:Number}", type_converters) with pytest.raises(error_class): parser.parse("test meter-10") def test_with_pattern_and_regex_group_count_is_none(): # -- CORNER-CASE: Increase code-coverage. data_values = {"a": 1, "b": 2} @parse.with_pattern(r"[ab]") def parse_data(text): return data_values[text] parse_data.regex_group_count = None # ENFORCE: None # -- CASE: Unnamed-params parser = parse.Parser("test {:Data}", {"Data": parse_data}) assert_fixed_match(parser, "test a", (1,)) assert_fixed_match(parser, "test b", (2,)) assert_fixed_mismatch(parser, "test c") # -- CASE: Named-params parser2 = parse.Parser("test {value:Data}", {"Data": parse_data}) assert_match(parser2, "test a", "value", 1) assert_match(parser2, "test b", "value", 2) assert_mismatch(parser2, "test c", "value") def test_case_sensitivity(): r = parse.parse("SPAM {} SPAM", "spam spam spam") assert r[0] == "spam" assert parse.parse("SPAM {} SPAM", "spam spam spam", case_sensitive=True) is None def test_decimal_value(): value = Decimal("5.5") str_ = "test {}".format(value) parser = parse.Parser("test {:F}") assert parser.parse(str_)[0] == value def test_width_str(): res = parse.parse("{:.2}{:.2}", "look") assert res.fixed == ("lo", "ok") res = parse.parse("{:2}{:2}", "look") assert res.fixed == ("lo", "ok") res = parse.parse("{:4}{}", "look at that") assert res.fixed == ("look", " at that") def test_width_constraints(): res = parse.parse("{:4}", "looky") assert res.fixed == ("looky",) res = parse.parse("{:4.4}", "looky") assert res is None res = parse.parse("{:4.4}", "ook") assert res is None res = parse.parse("{:4}{:.4}", "look at that") assert res.fixed == ("look at ", "that") def test_width_multi_int(): res = parse.parse("{:02d}{:02d}", "0440") assert res.fixed == (4, 40) res = parse.parse("{:03d}{:d}", "04404") assert res.fixed == (44, 4) def test_width_empty_input(): res = parse.parse("{:.2}", "") assert res is None res = parse.parse("{:2}", "l") assert res is None res = parse.parse("{:2d}", "") assert res is None def test_int_convert_stateless_base(): parser = parse.Parser("{:d}") assert parser.parse("1234")[0] == 1234 assert parser.parse("0b1011")[0] == 0b1011 r1chardj0n3s-parse-334db14/tests/test_pattern.py000066400000000000000000000056031463175247200216210ustar00rootroot00000000000000import pytest import parse def _test_expression(format, expression): assert parse.Parser(format)._expression == expression def test_braces(): # pull a simple string out of another string _test_expression("{{ }}", r"\{ \}") def test_fixed(): # pull a simple string out of another string _test_expression("{}", r"(.+?)") _test_expression("{} {}", r"(.+?) (.+?)") def test_named(): # pull a named string out of another string _test_expression("{name}", r"(?P.+?)") _test_expression("{name} {other}", r"(?P.+?) (?P.+?)") def test_named_typed(): # pull a named string out of another string _test_expression("{name:w}", r"(?P\w+)") _test_expression("{name:w} {other:w}", r"(?P\w+) (?P\w+)") def test_numbered(): _test_expression("{0}", r"(.+?)") _test_expression("{0} {1}", r"(.+?) (.+?)") _test_expression("{0:f} {1:f}", r"([-+ ]?\d*\.\d+) ([-+ ]?\d*\.\d+)") def test_bird(): # skip some trailing whitespace _test_expression("{:>}", r" *(.+?)") def test_format_variety(): def _(fmt, matches): d = parse.extract_format(fmt, {"spam": "spam"}) for k in matches: assert d.get(k) == matches[k] for t in "%obxegfdDwWsS": _(t, {"type": t}) _("10" + t, {"type": t, "width": "10"}) _("05d", {"type": "d", "width": "5", "zero": True}) _("<", {"align": "<"}) _(".<", {"align": "<", "fill": "."}) _(">", {"align": ">"}) _(".>", {"align": ">", "fill": "."}) _("^", {"align": "^"}) _(".^", {"align": "^", "fill": "."}) _("x=d", {"type": "d", "align": "=", "fill": "x"}) _("d", {"type": "d"}) _("ti", {"type": "ti"}) _("spam", {"type": "spam"}) _(".^010d", {"type": "d", "width": "10", "align": "^", "fill": ".", "zero": True}) _(".2f", {"type": "f", "precision": "2"}) _("10.2f", {"type": "f", "width": "10", "precision": "2"}) def test_dot_separated_fields(): # this should just work and provide the named value res = parse.parse("{hello.world}_{jojo.foo.baz}_{simple}", "a_b_c") assert res.named["hello.world"] == "a" assert res.named["jojo.foo.baz"] == "b" assert res.named["simple"] == "c" def test_dict_style_fields(): res = parse.parse("{hello[world]}_{hello[foo][baz]}_{simple}", "a_b_c") assert res.named["hello"]["world"] == "a" assert res.named["hello"]["foo"]["baz"] == "b" assert res.named["simple"] == "c" def test_dot_separated_fields_name_collisions(): # this should just work and provide the named value res = parse.parse("{a_.b}_{a__b}_{a._b}_{a___b}", "a_b_c_d") assert res.named["a_.b"] == "a" assert res.named["a__b"] == "b" assert res.named["a._b"] == "c" assert res.named["a___b"] == "d" def test_invalid_groupnames_are_handled_gracefully(): with pytest.raises(NotImplementedError): parse.parse("{hello['world']}", "doesn't work") r1chardj0n3s-parse-334db14/tests/test_result.py000066400000000000000000000014541463175247200214620ustar00rootroot00000000000000import pytest import parse def test_fixed_access(): r = parse.Result((1, 2), {}, None) assert r[0] == 1 assert r[1] == 2 with pytest.raises(IndexError): r[2] with pytest.raises(KeyError): r["spam"] def test_slice_access(): r = parse.Result((1, 2, 3, 4), {}, None) assert r[1:3] == (2, 3) assert r[-5:5] == (1, 2, 3, 4) assert r[:4:2] == (1, 3) assert r[::-2] == (4, 2) assert r[5:10] == () def test_named_access(): r = parse.Result((), {"spam": "ham"}, None) assert r["spam"] == "ham" with pytest.raises(KeyError): r["ham"] with pytest.raises(IndexError): r[0] def test_contains(): r = parse.Result(("cat",), {"spam": "ham"}, None) assert "spam" in r assert "cat" not in r assert "ham" not in r r1chardj0n3s-parse-334db14/tests/test_search.py000066400000000000000000000010121463175247200213770ustar00rootroot00000000000000import parse def test_basic(): r = parse.search("a {} c", " a b c ") assert r.fixed == ("b",) def test_multiline(): r = parse.search("age: {:d}\n", "name: Rufus\nage: 42\ncolor: red\n") assert r.fixed == (42,) def test_pos(): r = parse.search("a {} c", " a b c ", 2) assert r is None def test_no_evaluate_result(): match = parse.search( "age: {:d}\n", "name: Rufus\nage: 42\ncolor: red\n", evaluate_result=False ) r = match.evaluate_result() assert r.fixed == (42,)