in reply to Regexp: Only tr second occurance
Delete nth occurrence of .0:
my $n = 2; my $pattern = qr/\.0/; my $string = "This is the .0 test .0 string .0"; $string = delete_nth( $string, $pattern, $n ); print $string, "\n"; sub delete_nth { my ( $str, $pat, $n ) = @_; $n--; $str =~ s/($pat.*?){$n}($pat)/$1/; return $str; }
I tested it with a few simple test strings. One thing to note is that it won't work if $n == 1. But for any value of $n >= 2, it's fine.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regexp: Only tr second occurance
by Aristotle (Chancellor) on Jan 02, 2004 at 17:47 UTC |