Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
I have been struggling with a simple (or so I thought) regex for a day now and have only succeeded in confusing myself. Here's the scenario:
A user supplied string may contain 1 or more of the characters smtwhfa in any order. That's as easy as
$string =~ /^[smtwhfa]*$/
But this allows for duplicate characters and I need to be sure that no character is in the string more than once. For example:
swma is OK
smsa is NOT OK

I tried many variations of what I thought could work but to no avail. So, of course man perlre was my next stop. Then searches on Perl Monks and Google and then the camel book. The one thing that seemed to be the answer was a negative lookahead assertion but I don't really understand it. I'm not even sure if this the road I need to take.
Here is some of what I tried:
$string =~ /^[smtwhfa]*(?![smtwhfa])$/ $string =~ /^[s{1}m{1}t{1}w{1}h{1}f{1}a{1}]*$/ $string =~ /^([smtwhfa])(?!\1)*$/
And numerous other more embarrassing attempts.

I know there are other ways of doing this like this very ugly and inefficient example:
my $string = "smasm"; my @array = split(//, $string); my %hash; foreach(@array) { $hash{$_} ++; } foreach(keys %hash) { if($hash{$_} > 1) { print "ERROR\n"; last; } }
But I would really like to do this with a single regex so that it easily portable to other languages.

Any hints or examples that might lead me in the right direction will be greatly appreciated.

In reply to Regex (lookahead) Confusion by ChrisR

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-25 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found