#!/usr/bin/env perl use 5.034; my $text = <<'EOT'; This is an appt: 1203 So is 1001. But 8675 is not. EOT chomp($text); my $digits_4_re = qr{ (? 1, 1203 => 1, ); sub _anchor_if_apt { my $candidate = shift; if ( exists $valid_appt_numbers{$candidate} ) { return _anchor_for_num($candidate); } else { return $candidate; } } sub _anchor_for_num { my $unit = shift; return qq{$unit}; } $text =~ s{($digits_4_re)}{ _anchor_if_apt( $1 ) }xsmeg; say $text; exit 0; __END__ $ perl texty.plx This is an appt: 1203 So is 1001. But 8675 is not.