in reply to searching for a string w/ a * in any single position?

The best solution is not to come up with a single regexp, but have a solution to generate those regexp's. A big benefit: the code will be reusable.

  • Comment on Re: searching for a string w/ a * in any single position?

Replies are listed 'Best First'.
Re^2: searching for a string w/ a * in any single position?
by ikegami (Patriarch) on Oct 05, 2007 at 22:49 UTC

    I think the following will do the trick:

    my @chars = map quotemeta, split //, $word; my $re = join '|', map { local @_ = @chars; $_[$_] = '.'; join '', @_ } 0..$#chars;

    Using Regexp::Assemble should be faster:

    use Regexp::Assemble qw( ); my @chars = map quotemeta, split //, $word; my $ra = Regexp::Assemble->new(); for (0..$#chars) { local @_ = @chars; $_[$_] = '.'; $ra->add(join '', @_) } my $re = $ra->re();
      Generalizing this approach for Hamming distance > 1, using the combinations iterator from Iterating over combinations:
      sub gen_regex { my ($target, $n) = @_; my @chars = split //, $target; my $ra = Regexp::Assemble->new(); my $iter = combinations( $n => [ 0 .. $#chars ] ); while (my @c = $iter->()) { local @_ = @chars; $_[$_] = '.' for @c; $ra->add( join '', @_ ); } $ra->re(); }

      blokhead