Showing posts with label nth occurance. Show all posts
Showing posts with label nth occurance. Show all posts

Jan 25, 2019

Python substitute nth occurance

import re

##Substitue 3rd occurrence of 'python' with 'PYTHON'

nth_occurance = 3
text = 'python is good, python is better, python is best';

count = text.count('python')
if count <= 1:
print re.sub('python', r'PYTHON', text)
else:
print re.sub('^((.*?python.*?){' + str(nth_occurance-1) + '})python', r'\1PYTHON', text)


Output:
python is good, python is better, PYTHON is best

Jun 22, 2008

substitute for n'th occurance

#!F:\Perl\bin\perl -w
use strict;

# Substitue 3rd occurance of 'perl' with 'PERL'
my $text = 'perl is good, perl is better, perl is best';
print "\n INPUT Text:", $text;

my $nth_occurance = 3;
my $count=0;

$text =~ s{(perl)}{
++$count == $nth_occurance ? 'PERL' : $1
}ige;

print "\n OUTPUT Text:", $text,"\n";