If it takes me longer than five minutes or so to remember something or to look it up, I’ll probably blog it.
I wanted to expand character ranges like ‘a-z’ into their explicit ‘abcdefghijklmnopqrstuvwxyz’ versions, and I wanted to do it in a single regexp. I figured this would need a call to a subroutine to do the actual expansion, but couldn’t remember how to get the regexp to do that. I wasted a fair bit of time reading the stuff about (?{ code }) expressions in the perlre man page, but that’s for running arbitrary code on the left-hand side, in the pattern to be matched.
What really I wanted was the /e flag, which makes the right-hand side evaluate as Perl:
$string =~ s/([^\\])-(.)/expandpair($1, $2)/eg;
July 25, 2008 at 5:23 am
$ba =~ s/(.)-(.)/join(”,$1..$2)/eg;
July 25, 2008 at 5:28 am
Try again:
$ba =~ s/(.)-(.)/join(”,map {chr $_ } (ord($1)..ord($2)))/eg;
July 25, 2008 at 5:40 am
I put the expansion stuff in a subroutine so that it could do a bit of sanity checking on the range parameters. So it’s not strictly speaking a one-liner.
July 25, 2008 at 6:23 am
Your first suggestion comes much closer to working than I would have guessed: here’s the output for a couple of cases.
a-zA-Z => abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0-9 => 0123456789
0-Z => 0123456789
z-a => z
August 7, 2008 at 2:08 am
[...] regexps II August 7, 2008 — mrlynch This post described the littlest little language I’ve ever implemented, which would expand ranges like [...]
August 22, 2008 at 5:31 pm
[...] – bookmarked by 5 members originally found by miketung on 2008-08-10 Search and replace with an expression http://perlfunk.wordpress.com/2008/07/21/search-and-replace-with-an-expression/ – bookmarked by 1 [...]