Leo Leo - 1 year ago 85
Python Question

Regex to match PEP440 compliant version strings

PEP 440 lays out what is the accepted format for version strings of Python packages.

These can be simple, like:


Or complicated, like:

What is a suitable regex which could be used for finding and validating such strings?

Answer Source

I had the same question. This is the most thorough regex pattern I could find. PEP440 links to the codebase of the packaging library in it's references section.

pip install packaging

To access just the pattern string you can use the global

from packaging import version

See: https://github.com/pypa/packaging/blob/16.7/packaging/version.py#L159

# Deliberately not anchored to the start and end of the string, to make it
# easier for 3rd party code to reuse
    (?:(?P<epoch>[0-9]+)!)?                           # epoch
    (?P<release>[0-9]+(?:\.[0-9]+)*)                  # release segment
    (?P<pre>                                          # pre-release
    (?P<post>                                         # post release
    (?P<dev>                                          # dev release
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version

Of course this example is specific to Python's flavor of regex.