in reply to Replace part of a regex match

If you're really committed to the regexp, this works:

my $u = 'http://adserver.adtech.de/?addyn|2.0|323|91793|1|277|target=_ +blank'; print "$u\n"; $u =~ s/(.*\|.*\|.*\|.*\|.*\|).*(\|.*)/${1}976$2/; print "$u\n"; __END__ http://adserver.adtech.de/?addyn|2.0|323|91793|1|277|target=_blank http://adserver.adtech.de/?addyn|2.0|323|91793|1|976|target=_blank

You might also try using split and join:

my $u = 'http://adserver.adtech.de/?addyn|2.0|323|91793|1|277|target=_ +blank'; print "$u\n"; my @fields = split /\|/, $u; $fields[5] = 976; $u = join '|', @fields; print "$u\n"; __END__ http://adserver.adtech.de/?addyn|2.0|323|91793|1|277|target=_blank http://adserver.adtech.de/?addyn|2.0|323|91793|1|976|target=_blank

I also think it would be good to have a more specific expression. For example, instead of ".*", use "\d+" to make sure it's not an empty field and to make sure that it really does have digits and not some other junk you weren't expecting.

Replies are listed 'Best First'.
Re^2: Replace part of a regex match
by Bloodnok (Vicar) on Dec 23, 2008 at 23:04 UTC
    kyle, could the following change to the your regex be a little closer to what the OP sought...
    $u =~ s/(.*\|{5}).*(\|.*)/${1}976$2/;

    A user level that continues to overstate my experience :-))
      The regex expression .*\|{5} matches anything followed by exactly five '|' characters in a row, which is not what is present in the example of the OP.

      A regex something like the following might be better (although it is still a bit awkward):

      >perl -wMstrict -le "my $u = 'http://foo.bar.de/?baz|2.0|323|91793|1|277|fee=_fie'; print $u; $u =~ s{ \A ((?: [^|]* \|){5}) \d+ (\|.*) \z }{${1}976$2}xms; print $u; " http://foo.bar.de/?baz|2.0|323|91793|1|277|fee=_fie http://foo.bar.de/?baz|2.0|323|91793|1|976|fee=_fie
A reply falls below the community's threshold of quality. You may see it by logging in.