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

Here's the question: How can I make sure that a string contains ONLY certain characters? I want to ensure that a string only contains the characters:
a-z0-9_
So how do I check that?

Replies are listed 'Best First'.
Re: Pattern Matching
by chromatic (Archbishop) on Apr 03, 2000 at 23:52 UTC
    You can use a character class. What's a character class? It's a user-defined set of characters to match. For example, if you wanted your string to contain only characters between a and z, do this:
    if ($string =~ /^[a-z]+$/) { # we have a string of at least one character of the range a-z }
    You can also negate a character class with the ^ symbol at the start:
    if ($string =~ /[^a-z]/) { # if it contains even one character NOT in the range, it doesn't m +eet the criteria # do some error }
    That's probably your best bet. If you didn't mind A-Z as well, you could use \W, which matches non-word (\w) characters (which are A-Za-z0-9_). For more gritty details, see perlman:perlre.
RE: Pattern Matching
by Anonymous Monk on Apr 03, 2000 at 23:57 UTC
    Thanx. It's that second one I needed. Thanx a lot!
Re: Pattern Matching
by jbert (Priest) on Apr 06, 2000 at 16:32 UTC
    And don't forget that some nice character classes are predefined for you. Your example only has lower case a-z, but if that is an oversight then consider using '\w' to represent a 'word' character (defined as alphanumeric and '_').

    The general rule is that uppercasing the 'special' character class negates it. So \W is any 'non-word' character.

    Again, as pointed out above 'perlre' is a mine of information.