Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

regex maching unique character set

by mce (Curate)
on Jan 30, 2003 at 11:22 UTC ( [id://231260]=perlquestion: print w/replies, xml ) Need Help??

mce has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

This question might have been asked a million times, but here it is.

I want a regex to fail if there is:

1. A character not in the set

2. A character twice in the set

f.e.
The list of characters 'ABCDEF', than it should return false if.
ABDA
ABXD
AABB

But true if
ABC
A
DEFA

I now worked around with a map or grep, but I think it should be doable in a single regex. The sequence of characters doesn't matter

Thanks for your help
---------------------------
Dr. Mark Ceulemans
Senior Consultant
IT Masters, Belgium

Replies are listed 'Best First'.
Re: regex maching unique character set
by Corion (Patriarch) on Jan 30, 2003 at 11:31 UTC

    You want to use a backreference for the "twice" part. I punted on the "not in the set" part, and used an alternation for that. So my regex is really two parts :

    /([$set]).*\1/ # Look if there is any repetition or /[^$set]/ # Look if there is any unallowed character # Which combines to /([$set]).*\1|[^$set]/
    . Here's my test code :
    my $set = "ABCDEF"; for (<DATA>) { chomp; print "$_ vs. $set : ", $_ =~ m!([$set]).*\1|[^$set]! ? "Yes" : "No" +, "\n"; }; __DATA__ A B C ACX ABC AA BB
    perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
Re: regex maching unique character set
by broquaint (Abbot) on Jan 30, 2003 at 11:35 UTC
    This should do it
    use strict; my $cc = "ABCDEF"; my @false = qw(ABDA ABXD AABB); my @true = qw(ABC A DEFA); for(@false,@true) { my $res = /[^$cc] | ([$cc]) [$cc]* \1/x ? "no" : "yes"; print "$_: $res\n"; } __output__ ABDA: no ABXD: no AABB: no ABC: yes A: yes DEFA: yes

    HTH

    _________
    broquaint

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://231260]
Approved by broquaint
Front-paged by tye
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-03-28 18:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found