When I first read the OP, the phrase "matched pattern" triggered an "I know, I'll use a regex..." knee-jerk response, and I formulated the problem statement "keep the first n occurrences of a pattern in a string along with any intervening matter and delete all occurrences thereafter".

It turns out that a regex-based approach is not appropriate for the OPed problem unless it be a "keep all lines that match a given regex" strategy, which would, IMHO, be quite good because it combines a possibly quite large element of validation with data extraction and is also completely scaleable.

In any event, proceeding along the lines of my first-but-not-necessarily-best thought, I came up with this, which may be of interest:

>perl -wMstrict -le "my $s = 'x foo1 foo2 x foo3 x yfoo9 foo4 foo5 foo9y x foo6 foo7 x'; print qq{'$s' \n}; ;; my $pat = qr{ \b foo \d \b }xms; ;; for my $n (0 .. 4) { (my $t = $s) =~ s{ \A (?: .*? $pat){$n} \K | $pat }''xmsg; print qq{'$t'}; } " 'x foo1 foo2 x foo3 x yfoo9 foo4 foo5 foo9y x foo6 foo7 x' 'x x x yfoo9 foo9y x x' 'x foo1 x x yfoo9 foo9y x x' 'x foo1 foo2 x x yfoo9 foo9y x x' 'x foo1 foo2 x foo3 x yfoo9 foo9y x x' 'x foo1 foo2 x foo3 x yfoo9 foo4 foo9y x x'

Update: I should add that the  \K regex operator used above is available with Perl versions 5.10+.


In reply to Re: Removing matched pattern except the first pattern by AnomalousMonk
in thread Removing matched pattern except the first pattern by rahulruns

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.