my $fail; if ($str =~ /\b(?>(\d{1,3})(??{$fail ||= $1 > 255})\.?){4}/ && ! $fail) { # matched ... }