Python URL Pattern Matcher | Cododel
CODODELDEV
EN / RU
Back to Deck
[snippet]

Python URL Pattern Matcher

SOURCE Python
VERSION 1.0
AUTHOR Cododel

A simple, zero-dependency class to match URLs against patterns with named parameters. It converts patterns like /api/resource/<id> into regular expressions and extracts the parameters.

Usage

matcher = URLPatternMatcher('/api/users/<user_id>/posts/<post_id>')
result = matcher.match('/api/users/123/posts/456')
# Result: {'user_id': '123', 'post_id': '456'}

Source Code

import json
import re
class URLPatternMatcher:
def __init__(self, pattern: str):
self.pattern = pattern.rstrip('/')
def match(self, path: str) -> dict | bool:
"""Match URL pattern
Path format example: /api/automation/<service>/<entity>/<id>/<action>
"""
pattern_re = re.compile(r'(<([^>]+)>)')
matches = pattern_re.findall(self.pattern)
for match in matches:
self.pattern = self.pattern.replace(
match[0], fr'(?P<{match[1]}>[^/]+)')
print(self.pattern)
res = re.match(self.pattern, path)
if res:
return res.groupdict()
else:
return False
[ ▲ 0 ]