G'day Zu,

Welcome to the monastery.

I get the feeling that there's some aspect of this that you haven't told us about. For both strings, you have three capture groups but discard $2 in each case. Also, your replacements both have "\nfield2: valueB\n" hard-coded.

However, you've said "The regex below works"; on that basis, this solution is not "slow" for either string.

#!/usr/bin/env perl -l use strict; use warnings; use Time::HiRes qw{time}; my $no_field2 = "field1: valueA\nsome\nlines\nhere\nfield3: valueC\n" . "........................................\n" x 1000; my $has_field2 = "field1: valueA\nfield2: valueB\nfield3: valueC\n" . "........................................\n" x 1000; my $middle = "\nfield2: valueB\n"; my $re = qr{(^field1:.*?$).*?(^field3:)}ms; replace_middle($_, $middle, $re) for ($no_field2, $has_field2); sub replace_middle { my ($string, $middle, $re) = @_; print '-' x 40; print "Start:\n", substr $string, 0, 60; my $t0 = time; $string =~ s/$re/$1$middle$2/; my $t1 = time; print "Finish:\n", substr $string, 0, 60; print 'Time: ', $t1 - $t0; }

Output:

---------------------------------------- Start: field1: valueA some lines here field3: valueC .............. Finish: field1: valueA field2: valueB field3: valueC ............... Time: 6.89029693603516e-05 ---------------------------------------- Start: field1: valueA field2: valueB field3: valueC ............... Finish: field1: valueA field2: valueB field3: valueC ............... Time: 1.62124633789062e-05

-- Ken


In reply to Re: Efficient method to replace middle lines only when no match by kcott
in thread Efficient method to replace middle lines only when no match by Zu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.