in reply to Monks' Expression

My regular expression should take [id=###]blahblah[/id] and replace it with <a href="/cgi-bin/coolcode.pl?id=###">blahblah</a>.
The following should work:
my $text = "[id=###]blahblah[/id]; my $targetURL = "/cgi-bin/coolcode.pl?"; $text =~ s/.*[(id=.*)](.*)[\/id]/<a href=\"$targetURL\1\">\2<\/a>/gs;
  1. The backslash character escapes the quote and forward slash characters to make sure they are inserted literally into the target expression.
  2. the expressions between parentheses are stored as \1 and \2.
  3. the gs option ignores line breaks in the source and treats spaces as characters.

Replies are listed 'Best First'.
Re: Re: Monks' Expression
by I0 (Priest) on Jan 22, 2001 at 02:43 UTC
    $text =~ s/\[(id=.*?)](.*?)\[\/id]/<a href=\"$targetURL\1\">\2<\/a>/gs;
      $text =~ s#\[(id=[^\]]*)]([^\[]*)\[/id]#<a href="$targetURL$1">$2</a>#gs;
        $text =~ s#\[(id=[^]]*)]([^[]*)\[/id]#<a href="$targetURL$1">$2</a>#g;
      I want to thank I0 for correcting some bugs:
      1. '[' is apparently a reserved character in Perl REs so it needed to be escaped.
      2. The ? in .*? turns off greedy matching. Thus everything after id= will be matched but only up until the first '[' it encounters.