Re: Regular Expression Help?

From: David Fetter <david(at)fetter(dot)org>
To: SF Postgres <sfpug(at)postgresql(dot)org>
Subject: Re: Regular Expression Help?
Date: 2003-11-05 04:50:16
Message-ID: 20031105045016.GS14711@fetter.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: sfpug

On Tue, Nov 04, 2003 at 06:58:49PM -0800, David Wheeler wrote:
> On Tuesday, November 4, 2003, at 04:47 PM, David Fetter wrote:
>
> >On Tue, Nov 04, 2003 at 04:35:45PM -0800, Josh Berkus wrote:
> >>Currently, I'm doing 3
> >>substitutions, along the lines of:
> >
> >>$eline =~ s/#NAME/$ename/g;
> >>
> >>But that's not very sophisticated and I'd like to improve my use of
> >>regexp. Suggestions?
>
> It's not always the case that a single regex is more efficient or
> elegant than multiple regexen. For example, when I want to strip
> whitespace from the beginning _and_ end of a string, this:
>
> s/^\s+//;
> s/\s+$//;
>
> Is faster than:
>
> s/^\s+|\s+$//g;
>
> Or so I have read.

Very likely.

> >IMHO, your current system may be easier to maintain than this:
> >
> >%replacements = (
> > '#NAME' => $ename
> >, '#DATE' => $mdate
> >, '#DETAIL' => $edetail
> >);
> >
> >$eline =~ s/(#NAME|#DATE|#DETAIL)/$replacements{$1}/g;
> >
> >Or it may not. Anyhow, that's the way I'd set it up if I were
> >changing it :)
>
> This is probably how I would do it, too, though perhaps like this:
>
> >$eline =~ s/(#\w+)/$replacements{$1} || $1/ge;

I'd be a little scared to use this one because #\w+ matches more
things than I know about for sure.

> But it's possible that it's not any faster, because it has to do a
> hash lookup for each replacement. I would benchmark this against
> what you have. Of course, if what you need to maintain could change
> the # lines now and then, it's easiest to just edit a hash, rather
> than write more regexen.

Good point :)

It might be a little less maintenance to do something like

$match = qr{ "(". join("|", keys %replacements) . ")" }o;

$eline =~ s/$match/$replacements{$1}/g;

Cheers,
D
--
David Fetter david(at)fetter(dot)org http://fetter.org/
phone: +1 510 893 6100 cell: +1 415 235 3778

In response to

Responses

Browse sfpug by date

  From Date Subject
Next Message David Wheeler 2003-11-05 04:56:29 Re: Regular Expression Help?
Previous Message David Wheeler 2003-11-05 02:58:49 Re: Regular Expression Help?