Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Regex: matching character which happens exactly once

by QM (Parson)
on Oct 23, 2017 at 14:08 UTC ( [id://1201894]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1201894]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-24 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found