my $str= "1_abc/2_def/bla_30_31_blah"; my $count= 0; while( $str =~ /\d+_/g ) { last if 2 < ++$count; $str =~ s///; } print "\$str=($str)\n";
I believe that middle s/// is not doing what you think it is. It's going back to the beginning of the string, looking for the first match that matches the most recent successful regex match, and then removing it.

I think you lucked out on this one. Had your replacement been s//49_/, you would have seen only the first one changed, since the first replacement string would have been matched again on the second while-pass.

Oh, and even more so... I don't think your //g in the while is actually inching along! I think it's scanning from the beginning again as well, since you modify the scalar within the loop. So you just did this the hard way:

s/\d+_// for 1..2;
But that's not exactly what was asked for originally. It just happens to be good for this problem and this input data.

Well, it's what was literally asked for, but it's not very generalizable. {grin}

-- Randal L. Schwartz, Perl hacker


In reply to Re: (tye)Re: changing only the first two matches of a regex by merlyn
in thread changing only the first two matches of a regex by Anonymous Monk

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.