Skip to content

Instantly share code, notes, and snippets.

@websmithcode
Last active August 8, 2024 20:33
Show Gist options
  • Save websmithcode/7082d08b2789f29c71013e6807010dd4 to your computer and use it in GitHub Desktop.
Save websmithcode/7082d08b2789f29c71013e6807010dd4 to your computer and use it in GitHub Desktop.
URL Pattern Matcher on python - no dependencies
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
@websmithcode
Copy link
Author

Subscribe to my telegram channel, don’t miss new interesting solutions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment