Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

How do I find the Nth occurrence of a pattern?

( #2150=categorized question: print w/ replies, xml ) Need Help??
Contributed by vroom on Jan 18, 2000 at 23:42 UTC
Q&A  > regular expressions


Answer: How do I find the Nth occurrence of a pattern?
contributed by Roy Johnson

A recent discussion found this to be the fastest way, and it's pretty slick:

$_='abcabbcabbbbcabcabbcab'; my $n = 3; ## Find the $nth occurrence my $pat = qr/ab+/; ## of this pattern my ($NthMatch) = /(?:.*?($pat)){$n}/; print "Match #$n looks like $NthMatch\n";
The regex is: find the pattern (optionally preceded by something that isn't the pattern) n times. The pattern is in parens, so the final match will be returned.
Answer: How do I find the Nth occurrence of a pattern?
contributed by maverick

you could use =~ in array context like:

$string = "12 34 56 78 90 98 76 54 32 10"; (@matches) = ($string =~ /(\d+)/g); print "fifth match is $matches[4]\n"; print "eigth match is $matches[7]\n";

/\/\averick
Answer: How do I find the Nth occurrence of a pattern?
contributed by eak

Here is my monkified version of the nth_iter subroutine. You gotta love map{}.

#!/usr/bin/perl -w my @string = (34, 56, 78, 90, 98, 76, 54, 32, 10, 12, 13, 16, 19, 20, +10, 56); sub nth_iter{ my ($item, $n, $list) = @_; ( map { $string[$_] == $item ? $_ : (); } 0..$#string )[--$n] or -1; } print nth_iter(78, 1, \@string);
Answer: How do I find the Nth occurrence of a pattern?
contributed by vroom

Use the /g (global) to find all occurrences in a string. Place the matching statement within a while loop and count until you get to the wanted number.

$n=5; #want the 5th occurrence of a group of 5 numbers $count=0; while(/(\d{5})/g){ if(++$count==$n){ print "The $n\th occurrence was $1\n"; } }
Answer: How do I find the Nth occurrence of a pattern?
contributed by poolpi

With split

my $string = "12 34 56 78 90 98 76 54 32 10"; my $n = 3; print+ (split( /[^\d+]/, $string))[$n-1]; # output => 56 my $string ='abcabbcabbbbcabcabbcab'; my $n = 3; print+ (split( /[^(?:ab+)]/, $string ))[$n-1]; # output => abbbb
Answer: How do I find the Nth occurrence of a pattern?
contributed by Anonymous Monk

Here is a way to do this. This is more C than perl. I'd love for a monk to translate it. This defines a function that takes: the item to find, the teration to locate, an arry to search This returns the array index of the nth element. You get a -1 if none found.

@string = qw(34, 56, 78, 90, 98, 76, 54, 32, 10, 12, 13, 16, 19, 20, 1 +0, 56); sub nth_iter { my($item, $n, @list) = @_; $i = -1; $match = 0; $len = @list; while ($i++ < $len) { if($list[$i] == $item) { $match++; if ($match == $n) { last; } } } if ($match != $n) { $i = -1; } return $i; } print nth_iter(78, 1, @string);
Rock on! -Ty
Answer: How do I find the Nth occurrence of a pattern?
contributed by cLive ;-)

Haven't tested this, but liked the idea.... :)

my $n = whatever... my $i=0; while ( ($string =~ /PATTERN/g) && ($i < $n ) ) { $i++; } my $NthMatch = $1;

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others pondering the Monastery: (9)
    As of 2014-11-28 07:33 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      My preferred Perl binaries come from:














      Results (193 votes), past polls