Actually this will not work if the string includes numbers in the part that you match with \D. I think you have to "unroll the loop" if you want to avoid (.*?):

#!/bin/perl -w use strict; foreach( <DATA>) { s{^\d+_ # start then number(s) then _ ((?:\D*(?:\d(?!\d*_))?)*) # non_digits then optionnaly # a digit _not_ followed by dig +its and _ # repeat, rince... \d+_ # the second digit _ sequence (.*)} # the rest of the string {$1$2}x; print; } __DATA__ 1_abc/2_deg/bla_30_31_blah 1_ab1c/2_deg/bla_30_31_blah 1_ab1c/22_deg/bla_30_31_blah 1_a2b33c/22_deg/bla_30_31_blah a_ab1c/b_deg/bla_30_31_blah

Note that your regexp will not work properly for the second string. I also added a line where the regexp does not match as this can show bugs when a badly written regexp takes for ever to match on a string that it does not match.

Frankly it this case, and despite all the warnings around, I would use (.*?) and write the regexp as:

s/^\d_(.*?)\d_(.*)/$1$2/;

I would be happy to get enlightened as to why this is not safe by the way.


In reply to Re: Re: changing only the first two matches of a regex by mirod
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.