If you need a template that finds $n 'th 4-digit group, this works:
$pat = "^(?:.*?\\b(\\d{4})\\b){$n}"; if ($s =~ /$pat/) { print "Found $1\n"; } else { print "Not found\n"; }
I did this by building a string template, because I could not get the variable interpolated into the quantifier {$n} .
This pattern finds 4-digit groups that are on word boundaries (tests \b ); I do not know if this meets your requirements. Used in the template .*? to ensure the maximum possible number of characters between each four-digit group. The pattern is matched $n times, and the capture group $1 set to what was in the last iteration, i.e. $n 'th.
EDIT: When I just tried it again, it seemed like interpolating $n in the quantifier was just fine. I do not know what I did differently, that the last time it did not work. Maybe this will work:
if ($s =~ /^(?:.*?\b(\d{4}\b){$n}/) { ...
If not, see amon's comment on qr// .
ajb
source share