On Wed, 16 Feb 2022 at 14:47, Valentin Berlier <berlie...@gmail.com> wrote:
>
> Hi,
>
> I've been thinking that it would be nice if regex match objects could be 
> deconstructed with pattern matching. For example, a simple .obj parser could 
> use it like this:
>
>     match re.match(r"(v|f) (\d+) (\d+) (\d+)", line):
>         case ["v", x, y, z]:
>             print("Handle vertex")
>         case ["f", a, b, c]:
>             print("Handle face")
>
> Sequence patterns would extract groups directly. Mapping patterns could be 
> used to extract named groups, which would be nice for simple 
> parsers/tokenizers:
>
>     match re.match(r"(?P<number>\d+)|(?P<add>\+)|(?P<mul>\*)", line):
>         case {"number": str(value)}:
>             return Token(type="number", value=int(value))
>         case {"add": str()}:
>             return Token(type="add")
>         case {"mul": str()}:
>             return Token(type="mul")
>
> Right now, match objects aren't proper sequence or mapping types though, but 
> that doesn't seem too complicated to achieve. If this is something that 
> enough people would consider useful I'm willing to look into how to implement 
> this.

I'm not sure I really see the benefit of this, but if you want to do
it, couldn't you just write a wrapper?

>>> class MatchAsSeq(Sequence):
...     def __getattr__(self, attr):
...         return getattr(self.m, attr)
...     def __len__(self):
...         return len(self.m.groups())
...     def __init__(self, m):
...         self.m = m
...     def __getitem__(self, n):
...         return self.group(n+1)
...
>>> line = "v 1 12 3"
>>> match MatchAsSeq(re.match(r"(v|f) (\d+) (\d+) (\d+)", line)):
...     case ["v", x, y, z]:
...         print("Handle vertex")
...     case ["f", a, b, c]:
...         print("Handle face")
...
Handle vertex

Paul
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LCWHARNW5OOCY7CHCXC5CVGFH4OAFOEW/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to