parse() is the opposite of format()
.. code-block:: pycon
pip install parse
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(): https://docs.python.org/3/library/stdtypes.html#str.format
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.
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:
===== =========================================== ======== 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")
<Result (datetime.datetime(2023, 11, 23, 12, 56, 47),) {}>
>>> parse("{:%H:%M}", "10:26")
<Result (datetime.time(10, 26),) {}>
>>> parse("{:%Y/%m/%d}", "2023/11/25")
<Result (datetime.date(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...')
<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 special date and time types:
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
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.
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})
<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', {"Number": parse_number})
<Result () {'number': 42}>
>>> _ = 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})
<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', {"Number2": parse_number2})
<Result (42, 43) {}>
Otherwise, this may cause parsing problems with unnamed/fixed parameters.
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
.
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
case_sensitive
arg in compile (thanks @jacquev6)__contains__
for Result instances.pattern
attribute in user-defined types
(thanks Jens Engel)import *
export as it overwrites builtin.from parse import *
Format Specification Mini-Language
_
and removed the restriction on mixing fixed-position and named fieldsThis code is copyright 2012-2021 Richard Jones richard@python.org See the end of the source file for the license of use.