Skip site navigation (1) Skip section navigation (2)

Re: Regular Expression Help?

From: David Wheeler <david(at)kineticode(dot)com>
To: Josh Berkus <josh(at)agliodbs(dot)com>
Cc: SF Postgres <sfpug(at)postgresql(dot)org>
Subject: Re: Regular Expression Help?
Date: 2003-11-05 02:58:49
Message-ID: FAEBB7DB-0F3B-11D8-B9C0-0003931A964A@kineticode.com (view raw or flat)
Thread:
Lists: sfpug
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.

> 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;

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.

HTH,

David

-- 
David Wheeler                                     AIM: dwTheory
david(at)kineticode(dot)com                              ICQ: 15726394
http://www.kineticode.com/                     Yahoo!: dew7e
                                                Jabber: Theory(at)jabber(dot)org
Kineticode. Setting knowledge in motion.[sm]


In response to

Responses

sfpug by date

Next:From: David FetterDate: 2003-11-05 04:50:16
Subject: Re: Regular Expression Help?
Previous:From: eleinDate: 2003-11-05 00:53:29
Subject: Re: Regular Expression Help?

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group