http://qs321.pair.com?node_id=1201894


in reply to Regex: matching character which happens exactly once

For the sake of completeness, I submit one of the solutions I don't think you want, namely, creating a regex for each character of the possible alphabet.

This wasn't as easy as I thought it would be, because capturing the actual match requires filtering out all of the unmatch (undef) alternatives. Perhaps someone can improve on this idea?

#!/usr/bin/env perl # # Match a char only occuring once in a string. # See https://perlmonks.pairsite.com/?node_id=1201795 use strict; use warnings; my @alpha = ('a'..'b'); my $alpha = join(',', @alpha); my @input = glob "{$alpha}" x 12; my @regex; for my $c (@alpha) { my $d = quotemeta($c); push @regex, "(?:[^$d]*)([$d])(?:[^$d]*)"; } my $once = join('|', @regex); my $matches; my $attempts; for my $i (@input) { my(@catch) = $i =~ /^(?:$once)$/; if (@catch) { my $catch = join('', grep {defined($_)} @catch); # printf "(%s) => (%s)\n", $catch, $i; $matches++; } $attempts++; } printf "matches: %s/%s\n", $matches, $attempts; exit; # Output: # > pm1201795.pl # matches: 24/4096

-QM
--
Quantum Mechanics: The dreams stuff is made of