Soumya
Soumya

Reputation: 893

Regex - substitute doesn't replace even though the regex matches properly

Trying to replace [[http://someUrl.com][link]] with <a href="http://someUrl.com">link</a>

The regex matches properly and I can see the $1,$2,$3 set properly.

$1:[[http://someUrl.com][link]] $2:http://someUrl.com $3:link

foreach my $pText("line1 [[http://google.com][google]] end","line2 [[http://someUrl.com][link]] end"){
     my $pTemp = $pText;
     print "\n".$pTemp."\n";
     if ($pTemp =~ /(\[\[((?:http|https|ftp|file|gopher|irc|news|mailto|nntp|telnet)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?::[a-zA-Z0-9]*)?\/?[a-zA-Z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~]*)\]\[(.*?)\]\])/){
         print "MATCHED  : $1 >> $2 >> $3\n";
         #$pTemp =~ s/$1/<a href="$2">$3<\/a\>/;
         $pTemp =~ s/$1/NEED TO REPLACE/;
         print "MODIFIED : $pTemp\n\n";
     }
}

Strangely it results in

line1 [[http://google.com][google]] end
MATCHED  : [[http://google.com][google]] >> http://google.com >> google
MODIFIED : line1 [[http://google.com][googNEED TO REPLACE] end


line2 [[http://someUrl.com][link]] end
MATCHED  : [[http://someUrl.com][link]] >> http://someUrl.com >> link
MODIFIED : line2 [[http://someUrl.com][link]] end

I am not sure why the substitution is failing even though the regex matches the strings properly. Any pointers will be a great help.

Upvotes: 0

Views: 79

Answers (1)

elbows
elbows

Reputation: 219

The first argument of s// is interpreted as a regexp, so the "[" and "]" characters in your match are screwing things up. You can use '\Q' to escape them:

$pTemp =~ s/\Q$1/NEED TO REPLACE/;

Upvotes: 1

Related Questions