Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Regex: matching character which happens exactly once

by QM (Parson)
on Oct 23, 2017 at 14:08 UTC ( #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 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: # > # matches: 24/4096

Quantum Mechanics: The dreams stuff is made of

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2021-04-12 19:23 GMT
Find Nodes?
    Voting Booth?

    No recent polls found