Perl Regex substitution: replace nth occurrance

Y

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.
 
J

John W. Krahn

Yogi said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top