use strict; use warnings; my $qbf = q{The quick brown fox jumps over the lazy dog. }; (my $qbfForRX = $qbf) =~ s{\s}{\\s}g; my $message = $qbf x 7 . qq{\n} . ($qbf. qq{\n}) x 2 . $qbf . qq{\n} . $qbf x 6 . qq{\n}; print $message, qq{\n}; my $rxToChange = qr {(?x) # Use extended syntax (?: # Non-capture group # for alternation # Either ... (?<=\n)(?=$qbfForRX) # Move engine to point # preceded by newline # and followed by # phrase | # ... or ... (?<=)(?=$qbfForRX) # Move engine to point # preceded by # and followed by # phrase ) # Close non-capture # group ($qbfForRX) # Capture phrase (?=(?:\n|)) # If followed by either # newline or }; $message =~ s{$rxToChange}{$^N}g; print $message; #### The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.