Skip to content

Instantly share code, notes, and snippets.

@Tishka17
Created September 3, 2024 14:51
Show Gist options
  • Save Tishka17/575572dc5a6d51069981410ba2767bb0 to your computer and use it in GitHub Desktop.
Save Tishka17/575572dc5a6d51069981410ba2767bb0 to your computer and use it in GitHub Desktop.
regex match case
import re
class R:
def __init__(self, value):
self._value = value
class MatchRegex(type):
def __instancecheck__(cls, obj):
if not isinstance(obj, R):
raise TypeError("R expected")
regex: re.Pattern = cls._regex
if match := regex.fullmatch(obj._value):
for name, value in match.groupdict().items():
setattr(obj, name, value)
return True
def matcher(regex):
class Tmp(metaclass=MatchRegex):
_regex = re.compile(regex)
return Tmp
R1 = matcher(r"(?P<a>\w+) - (?P<b>\w+)")
R2 = matcher(r"(?P<a>\w+)")
match R("1 - 2"):
case R1(a=a, b=b):
print("matched r1", a, b)
case R2(a=a):
print("matched r2", a)
case _:
print("no match")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment