If you want a pattern that finds the $n
'th 4-digit group, this seems to work:
$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 pattern because I couldn't get a variable interpolated into a quantifier {$n}
.
This pattern finds 4-digit groups that are on word boundaries (the \b
tests); I don't know if that meets your requirements. The pattern uses .*?
to ensure that as few characters as possible are matched between each four-digit group. The pattern is matched $n
times, and the capture group $1
is set to whatever it was in the last iteration, i.e. the $n
'th one.
EDIT: When I just tried it again, it seemed to interpolate $n
in a quantifier just fine. I don't know what I did differently that it didn't work last time. So maybe this will work:
if ($s =~ /^(?:.*?\b(\d{4}\b){$n}/) { ...
If not, see amon's comment about qr//
.