repath
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
- gotcha The library has not been updated since October 2019. While it may still function, there's a risk of compatibility issues with newer Python versions (e.g., Python 3.8+) or modern web frameworks. Users should test thoroughly.
- gotcha The package name `repath` can be easily confused with other Python libraries such as `rpath`, `rpaths`, `multipath`, or Django's `re_path` function, which serve different purposes related to file paths or URL routing with raw regular expressions.
- gotcha The PyPI classifier includes 'Programming Language :: Python :: 2', indicating historical Python 2 compatibility. Although a Python 3 wheel is available, reliance on older design patterns might exist, potentially causing subtle issues in Python 3-only environments.
Install
-
pip install repath
Imports
- repath
import repath
Quickstart
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.