A case-like macro for regular expressions
I often find myself wanting a simple case
-like macro where the keys are regular expressions. regex-case
is an attempt at this.
I use CL-PPCRE for the usual things regular expressions are useful for, and probably for some of the things they should not really be used for as well. I often find myself wanting a case
like macro, where the keys are regular expressions. There is a contributed package for Trivia which will do this, but Trivia is pretty overwhelming. So I gave in and wrote regex-case
which does what I want.
regex-case
is a case
-like macro. It looks like
(regex-case <thing>
(<pattern> (...)
<form> ...)
...
(otherwise ()
<form> ...))
Here <pattern>
is a literal regular expression, either a string or in CL-PPCRE’s s-expression parse-tree syntax for them. Unlike case
there can only be a single pattern per clause: allowing the parse-tree syntax makes it hard to do anything else. otherwise
(which can also be t
) is optional but must be last.
The second form in a clause specifies what, if any, variables to bind on a match. As an example
(regex-case line
("fog\\s+(.*)\\s$" (:match m :registers (v))
...)
...)
will bind m
to the whole match and v
to the substring corresponding to the first register. You can also bind match and register positions. A nice (perhaps) thing is that you can not bind some register variables:
(regex-case line
(... (:registers (_ _ v))
...)
...)
will bind v
to the substring corresponding to the third register. You can use nil
instead of _
.
The current state of regex-case
is a bit preliminary: in particular I don’t like the syntax for binding thngs very much, although I can’t think of a better one. Currently therefore it’s in my collection of toys: it will probably migrate from there at some point.