Perl Regex substitution: replace nth occurrance
Perl Regex substitution: replace nth occurrance
am 09.04.2008 08:44:29 von yogi
Hi Guys,
I have a variable say:
$x = "this is test program with test inputs";
My requirement is to replace nth occurrance of "test" with something
else. how to achieve the same using perl regex. if i do something
like:
$x =~ s/test/java/g;
This is going to replace all occurrance of test with "java" but my
requirement is to replace say 2nd occurrance only. Any help?
Regards.
Re: Perl Regex substitution: replace nth occurrance
am 09.04.2008 09:05:07 von Frank Seitz
Yogi wrote:
> I have a variable say:
> $x = "this is test program with test inputs";
>
> My requirement is to replace nth occurrance of "test" with something
> else. how to achieve the same using perl regex. if i do something
> like:
> $x =~ s/test/java/g;
>
> This is going to replace all occurrance of test with "java" but my
> requirement is to replace say 2nd occurrance only. Any help?
perldoc -q nth
Frank
--
Dipl.-Inform. Frank Seitz; http://www.fseitz.de/
Anwendungen für Ihr Internet und Intranet
Tel: 04103/180301; Fax: -02; Industriestr. 31, 22880 Wedel
Re: Perl Regex substitution: replace nth occurrance
am 09.04.2008 10:12:10 von yogi
On Apr 9, 12:05 pm, Frank Seitz wrote:
> Yogi wrote:
> > I have a variable say:
> > $x =3D "this is test program with test inputs";
>
> > My requirement is to replace nth occurrance of "test" with something
> > else. how to achieve the same using perl regex. if i do something
> > like:
> > $x =3D~ s/test/java/g;
>
> > This is going to replace all occurrance of test with "java" but my
> > requirement is to replace say 2nd occurrance only. Any help?
>
> perldoc -q nth
>
> Frank
> --
> Dipl.-Inform. Frank Seitz;http://www.fseitz.de/
> Anwendungen für Ihr Internet und Intranet
> Tel: 04103/180301; Fax: -02; Industriestr. 31, 22880 Wedel
Thanks Frank for your help. :)
Regards,
-Yogi
Re: Perl Regex substitution: replace nth occurrance
am 09.04.2008 20:08:43 von someone
Yogi wrote:
> Hi Guys,
> I have a variable say:
> $x = "this is test program with test inputs";
>
> My requirement is to replace nth occurrance of "test" with something
> else. how to achieve the same using perl regex. if i do something
> like:
> $x =~ s/test/java/g;
>
> This is going to replace all occurrance of test with "java" but my
> requirement is to replace say 2nd occurrance only. Any help?
$ perl -le'
my $test = q[ 1 test 2 test 3 test 4 test 5 test 6 test 7 test ];
print $test;
my $count;
my $to_java = 4;
while ( $test =~ /test/g ) {
if ( $to_java == ++$count ) {
substr $test, $-[0], $+[0] - $-[0], q[java];
}
}
print $test;
'
1 test 2 test 3 test 4 test 5 test 6 test 7 test
1 test 2 test 3 test 4 java 5 test 6 test 7 test
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall