abubacker has asked for the wisdom of the Perl Monks concerning the following question:

Dear all ,

1-hai 2-hai 3-hai 4-hai(this pattern needs to be matched )

I want a regular expression which is to match the 4th occurrence of hai ( in this example ),
Actually I want a method to match the nth occurrence of a pattern in a string.
can I achieve this using perl regular expression in a straight forward manner
please help me out !

Replies are listed 'Best First'.
Re: match the nth pattern
by JavaFan (Canon) on Aug 18, 2009 at 10:24 UTC
    There's no special syntax or functionality to do this. So you have to do it yourself. And it depends whether you want the nth non-overlapping, or the nth overlapping match. For instance, the line "hahahaha" has 2 non-overlapping matches of "haha", but three overlapping. For non overlapping, this may work for you:
    ($str =~ /hai/g)[3]; # Fourth match
    For overlapping, try:
    ($str =~ /(?=(hai))/g)[3]; # Fourth match
Re: match the nth pattern
by BioLion (Curate) on Aug 18, 2009 at 10:28 UTC

    What have you tried so far?

    A simple solution might to be match all occurrences and then select which you want to keep :

    use strict; use warnings; my $string = '1potato 2potato 3potato 4 potato'; print +( $string =~ m/(\d+potato)/g )[2];

    Just a something something...