repath

0.9.0 · maintenance · verified Wed Apr 15

repath is a Python library that ports the pathToRegexp Node.js module, designed to generate regular expressions from ExpressJS-style path patterns. It enables parsing paths and extracting parameters using Python's named capture groups. The current version is 0.9.0, released in October 2019, and the project appears to be in maintenance mode due to its last update date.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `repath` to convert ExpressJS-style path patterns into Python regular expressions, match URLs against these patterns to extract parameters, and generate paths from parameters using the reverse compilation.

import repath

# Define an ExpressJS-style path pattern
path_pattern = "/user/:id/posts/:post_id"

# Generate a regular expression and a list of keys (parameters)
regexp, keys = repath.repath(path_pattern)

print(f"Generated Regex: {regexp.pattern}")
# Example output: ^\/user\/(?:([^\/]+?))\/posts\/(?:([^\/]+?))\/?$

# Match a URL against the generated regex
url_to_match = "/user/123/posts/456"
match = regexp.match(url_to_match)

if match:
    print(f"Matched groups: {match.groups()}")
    # Example output: ('123', '456')
    print(f"Matched parameters: {match.groupdict()}")
    # Example output: {'id': '123', 'post_id': '456'}
else:
    print("URL did not match the pattern.")

# You can also compile tokens to generate paths (reverse operation)
tokens = repath.repath_tokens("/files/:name(\\d+)") # Path with a regex constraint
compiler = repath.tokens_to_function(tokens)

print(f"Compiled path: {compiler({'name': '789'})}")
# Example output: /files/789
# Note: This will raise ValueError if constraints are not met.

view raw JSON →