in reply to Replacing nth occurrence of string

Hi,
#!/usr/bin/perl -w use strict; my $delimiter = ';'; my $nth = 3; my $regex = '^(' . ".*$delimiter"x$nth . ')'; while (<DATA>) { s/$regex/$1$delimiter/ && print; } __DATA__ col1;col2;col3;col4 aaa;bbb;ccc;ddd AAA;BBB;CCC;DDD

Output is then:
col1;col2;col3;;col4 aaa;bbb;ccc;;ddd AAA;BBB;CCC;;DDD
Regards,
svenXY

Replies are listed 'Best First'.
Re^2: Replacing nth occurrence of string
by halley (Prior) on Sep 23, 2005 at 15:24 UTC
    When assembling regular expressions, beware: if $delimiter had any regex special characters, you would have to use \Q$delimiter\E in the assembled regex.
    my $delimiter = '.'; my $nth = 3; my $regex = '^(' . ('.*\Q' . $delimiter . '\E') x $nth . ')';

    --
    [ e d @ h a l l e y . c c ]