[Melbourne-pm] Regular expression fun

Damian Conway damian at conway.org
Thu Sep 4 02:46:58 PDT 2014


One possible solution would be to use named captures to
identify each match (and to do so for all the possible matches at once).
Like so:

    my $names_pattern
        = join '|',
          map { my $name = $clients{$_};
                  my ($first, $initial, $last) = $name =~ /((.).*)\s+(.*)/;
                  my $names = join '|', reverse sort
                              ( "$first\\s+$last",
                              "$initial\\.?\\s+$last",
                              "$last,?\\s*(?:$first|$initial)",
                              );
                  "(?<_$_>$names)"
              }
          keys %clients;

    if ($page =~ m{\A(?:$names_pattern|.)*\Z}s) {
        use Data::Dumper 'Dumper';
        my @matched_ids = map {substr($_,1)} keys %+;

        for my $client_id (@matched_ids) {
            say "yay I matched $client_id";
        }
    }

Note that this might sometimes be significantly *slower*, as it
always has to examine the entire string, rather than short-circuiting
on each match.

Damian


More information about the Melbourne-pm mailing list