in reply to Regexp: Only tr second occurance

I haven't seen this one yet...

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
    That's easy to get around:
    sub delete_nth { my ( $str, $pat, $n ) = @_; my $cap = "$pat.*" x ( $n - 1 ); $str =~ s/($cap)$pat/$1/; return $str; }

    Makeshifts last the longest.