Search and replace with an expression

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;

6 Responses to “Search and replace with an expression”

  1. BKB Says:

    $ba =~ s/(.)-(.)/join(”,$1..$2)/eg;

  2. BKB Says:

    Try again:

    $ba =~ s/(.)-(.)/join(”,map {chr $_ } (ord($1)..ord($2)))/eg;

  3. mrlynch Says:

    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.

  4. mrlynch Says:

    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

  5. Range regexps II « perlfunk Says:

    [...] regexps II August 7, 2008 — mrlynch This post described the littlest little language I’ve ever implemented, which would expand ranges like [...]

  6. Bookmarks about Replace Says:

    [...] – 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 [...]


Leave a Reply