in reply to force regular expression to match every item only once

Your code doesn't compile. Please make always sure to post functional code.
The \1 wouldn't work here, at least I can't think how to use it between different regex calls ala / /g where you apply one regex several times. \1 can be used inside one regex to refer to an already matched part, but you actually don't do this here.
There is the experimental (?{ code }) construct which allows you to execute code inside the regex where you maybe could check if it already matched.

One better way would be to first match all patterns multiple times and then filter the list using a hash:

use strict; use warnings; my $word = "zezl"; my $dictword = "zezezl"; my @pairs = $word =~ /(?=(..))/g; my $matcher = qr/(?=(@{[join "|", @pairs]}))/; my %seen; my $matches = 0; my @matches; foreach my $match ($dictword =~ /$matcher/g) { if (not exists $seen{$match}) { $matches ++; push @matches, $match; } $seen{$match} = 1; } print "Matches: @matches\n"; print "$matches $dictword \n";
Here we iterate over the results and mark all matches as seen, but only count them the first time. In addition when you need the list of real matches you can push the first matches in an array like shown above.

Replies are listed 'Best First'.
Re^2: force regular expression to match every item only once
by hiddenOx (Novice) on Apr 21, 2008 at 02:49 UTC
    The main idea is to get every pair to get matched only once BUT if there are two pairs identical in the keyword and in the dictionary there are 2 identical keywords too, then every keyword will get matched once..

    I will try to elaborate:
    keyword:zezlze --> ze ez zl lz ze
    dicWord:zezezd --> ze ez ze ez zd

    so the score of this part should be 3 as the ze appears twice and each one is matched with the corresponding and the ez is matched once ONLY as second ez the dictionary word hasn't found another match in the keyword

    I hope that I explained well, if not, Please let me know.

    Thank you very much for your help
      Based on my last code, you could add a hash with the number of occurrence of every pair and then check if this pair was already matched this often:
      use strict; use warnings; my $word = "zezlze"; my $dictword = "zezezd"; my @pairs = $word =~ /(?=(..))/g; my %count; $count{$_}++ foreach (@pairs); my $matcher = qr/(?=(@{[join "|", @pairs]}))/; my %seen; my $matches = 0; my @matches; foreach my $match ($dictword =~ /$matcher/g) { if ($seen{$match}++ < $count{$match}) { $matches ++; push @matches, $match; } } print "Matches: @matches\n"; print "$matches $dictword \n";
      results in
      Matches: ze ez ze 3 zezezd