|
Prev: GET PAID MILLIONS OF DOLLARS FROM GOOGLE PROJECT NETWORK.IT ISA FREE PROGRAMME .THE LINK IS BELOW
Next: FAQ 8.37 How do I find out if I'm running interactively or not?
From: Yogi on 9 Apr 2008 02:44 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.
From: Frank Seitz on 9 Apr 2008 03:05 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
From: Yogi on 9 Apr 2008 04:12 On Apr 9, 12:05 pm, Frank Seitz <devnull4...(a)web.de> wrote: > 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 Thanks Frank for your help. :) Regards, -Yogi
From: John W. Krahn on 9 Apr 2008 14:08
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 |