in reply to RE: Selective substitution: not in Perl?
in thread Selective substitution: not in Perl?

I was going to give a similar solution, but then I realised that the previous (non-replaced) matches didn't necessarily have to be consecutive in the original string. Perhaps you you need to put optional separator space in the regex. Something like...

$string =~ s/^(($pattern.*){$n})$pattern/$1$better/;
--
<http://www.dave.org.uk>

European Perl Conference - Sept 22/24 2000, ICA, London
<http://www.yapc.org/Europe/>

Replies are listed 'Best First'.
RE: RE: RE: Selective substitution: not in Perl?
by nuance (Hermit) on Aug 16, 2000 at 14:49 UTC
    The .* is greedy, as far as I can see that will always replace ithe last match if you have more than the number you need.
    my string = "foo_a_foo_b_foo_c_foo_d_foo_e_foo_f_foo" my $pattern = "foo" my $better = "bar" my $n = 1; $string =~ s/^(($pattern.*){$n})$pattern/$1$better/;
    would give:
    "foo_a_foo_b_foo_c_foo_d_foo_e_foo_f_bar"
    not
    "foo_a_bar_b_foo_c_foo_d_foo_e_foo_f_foo"

    Nuance

      You're absolutely right, of course. Now I remember why I didn't post that solution in the first place :(

      Update:

      On thinking about it further, I realise that:

      $string =~ s/^(($pattern.*?){$n})$pattern/$1$better/;

      will probably do the trick.

      --
      <http://www.dave.org.uk>

      European Perl Conference - Sept 22/24 2000, ICA, London
      <http://www.yapc.org/Europe/>