OK, I'm a perl newbie, and I'm glad you folks are around.

I'd have thought this question had an easy answer, but my research just revealed nothing. Here's the issue:

Take a substitution command as follows:

$abcd =~ s/ab/cd/i;

As above, it'll match the first "ab" and change it to "cd" Easy. ok, to make it work on every instance of "ab" in the doc, change it to this by adding the "g":

$abc =~ s/ab/cd/gi;

But what if I want it to match UP TO the first 5 instances when I'm not sure how many instances are in the doc? Lets say there may be 1 or 4 or 7 or twenty instances, but in all cases I just want up to the first 5?

I've seen the following notation:

* - Match zero or more times
+ - Match one or more times
? - Match zero or one time
{X} - Match X times EXACTLY.
{X,} - Match X or more times
{X,Y} - Match X to Y times

But for example, the "match X to Y times" won't work for me if the document contains more than Y instances, and I only want the first 5. It'll only MATCH if the required ranges exist--apparently has nothing to do with the number of substitutions actually made, which will be zero if the instances don't fall within the range...

OK, once more, lest I've confused you. I want the substitution to occur only on the first 5 instances, or fewer, if fewer than 5 exist.

Surely there's an easy way to do this?


In reply to pattern matching a limited number of times by bob49

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.