in reply to Monks' Expression

I've only got a moderate amount of experience working with perl, so my coding isn't always the best, but here's one approach to it...
my $text = "Here is [id=327]a very cool document[/id] for you"; $text =~ /\[id=([0-9]*)\](.*)\[\/id\]/i; my $tag = "<A HREF=\"/cgi-bin/coolcode.pl?id=$1\">$2</A>"; my $before = $`; my $after = $'; print "$before$tag$after\n";
If you actually put this in a file and run it with Perl, you'll get:
Here is <A HREF="/cgi-bin/coolcode.pl?id=327">a very cool document</A> + for you
Just as you'd expect and (hopefully) want. :-)

Replies are listed 'Best First'.
Re: Re: Monks' Expression
by eg (Friar) on Jan 22, 2001 at 13:34 UTC

    Interesting. As has been mentioned before, .* here is bad because it's greedy and will prevent you from finding two matches on a line. Furthermore, .* is usually pretty inefficient -- the regexp has to match everything to the end of the line and then start backtracking to try to match whatever follows the .*. (.*? is better but still less than ideal to because it needs to look ahead one character in every step. If '[' is only allowed in tags, then [^[]* is the best.)

    Also, why use $before and $after rather than $` and $' directly? Of course, if at all possible, you shouldn't be using $` and $' at all (see Why does using $&, $`, or $' slow my program down? in perlfaq6).

    Cheers, mate!

      I used $before and $after because often, I've found, I end up using multiple regexps in one block of code, and I need to easily get back to those values from prior matches. Thanks for the tips though, I was hoping for some advice on my regexps. :-)