Hammy has asked for the wisdom of the Perl Monks concerning the following question:

Sorry for such a simple question, but I can not get the syntax correct. I am trying to search the string

aab"123"bcc abc="123" abc="345" aab"123"bcc

for the string

abc="123"

to replace it with

abc="123" aabbcc
  • Comment on How do I search and replace a string with quotes

Replies are listed 'Best First'.
Re: How do I search and replace a string with quotes
by tadman (Prior) on Jul 26, 2001 at 18:51 UTC
    How about:
    s/(abc="123")/$1 aabbcc/;
    The $1 is merely the "memorized" version of the first part of the substitution.

    If you are having trouble putting quotes in your strings, that is another problem. Make sure you either escape them, using backslash, or you declare those strings with single quotes.
Re: How do I search and replace a string with quotes
by Hofmator (Curate) on Jul 26, 2001 at 18:54 UTC

    Just do something like this

    my $string = q/aab"123"bcc abc="123" abc="345" aab"123"bcc/; $string =~ s/(abc="123")/$1 aabbcc/; # or better (doesn't do unnecessary replacing) $string =~ s/(?<=abc="123")/ aabbcc/; __END__ Benchmark: timing 300000 iterations of lookback, normal... lookback: 4 wallclock secs ( 4.32 usr + 0.01 sys = 4.33 CPU) @ 69 +348.13/s (n=300000) normal: 6 wallclock secs ( 6.01 usr + 0.02 sys = 6.03 CPU) @ 49 +759.50/s (n=300000) Rate normal lookback normal 49759/s -- -28% lookback 69348/s 39% --

    A suggestion for the next time, post some code (and the error message you get) so that we can see what you have so far ...

    Update: AM is right, the positive lookahead was wrong. I replaced it with a lookbehind and now it works. To show the benefit I also included a small benchmark. As is always the case with benchmarks - results vary depending on the length of the text being replaced.

    -- Hofmator

      $string =~ s/(?=abc="123")/ aabbcc/;
      does the same as:
      $string =~ s/(abc="123")/ aabbcc$1/;
      which is not correct.