Employing a little regex look ahead trickery gives something like this:
use strict; use warnings; my $pat = 'ono'; my $str = <<STR; ono is the pattern to match. ono is found once in onono STR #123456789012345678901234567890123456789012345678901234 # 1 2 3 4 5 for my $count (1..4) { if ($str =~ /(?:(?:(?!$pat).)*($pat)){$count}/) { print "Match at $-[1] for count = $count\n"; } else { print "No match for count = $count\n"; } }
Prints:
Match at 0 for count = 1 Match at 29 for count = 2 Match at 50 for count = 3 No match for count = 4
Note that at least simple regex matches are fine in the pattern including look ahead and look back matches, but avoid capture groups.
In reply to Re: search for nth occurrence of a pattern in a line
by GrandFather
in thread search for nth occurrence of a pattern in a line
by deepa
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |