Home: Perl Programming Help: Regular Expressions:
Regex substitute with capture not changing string



bulrush
User

Nov 18, 2015, 7:37 AM


Views: 21886
Regex substitute with capture not changing string

GOT IT WORKING. Problem solved.

Basically I'm trying to change a string in this format: '^1 <#cn1>' to this format: '[^1]'. Here's a tiny program for an example.

I thought I fixed it but my resulting string in $in, has backslashes, which I do not want. I'll test further.


Code
# test.pl 
my($in,$news,$num,$olds,$s,$t);

$in='blah blah blah.^1 <#fn1> blah blah blah';
$news='\[\^$1\]';
# Convert '^1 <#fn1>' to '[^1]'.
if ($in=~m/\^(\d+) <#fn\d+>/)
{
$olds=$&;
$num=$1;
$news='\[\^'.$1.'\]';
# Use \Q and \E if old string might contain backslashable ctrs.
$in=~s/\Q$olds\E/$news/;
print "\$in now is: $in\n";
}


Did I miss escaping some characters somewhere? Anyone have any idea how to make this work?

Thanks.
-----


(This post was edited by bulrush on Nov 18, 2015, 11:06 AM)


Laurent_R
Veteran / Moderator

Nov 18, 2015, 7:53 AM


Views: 21880
Re: [bulrush] Regex substitute with capture not changing string

Perhaps this (shown under the Perl debugger):

Code
  DB<1> $in = 'blah blah blah.^1 <#fn1> blah blah blah'; 

DB<2> $in =~ s/([^^]+)\^(\d+)\s+<#fn\d+>(.+)/$1\[\^$2]$3/;

DB<3> p $in
blah blah blah.[^1] blah blah blah