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

its been a while since i've used PERL. So i'm having troubles with a RE. I need to check a value to ensure there are no numbers, punctuations, and no more than 1 space in it. Can anyone please help me with this.
  • Comment on Need regex to check for disallowed characters

Replies are listed 'Best First'.
Re: Need regex to check for disallowed characters
by flyingmoose (Priest) on Apr 09, 2004 at 20:18 UTC
    It would be better to match what you will accept rather than what you will not accept. It's easier that way and will make your code easier to read and understand.

    if ($input =~ m/^[A-Za-z]*\s{0,1}[A-Za-z]*$/) { print "match!\n"; } else { print "no match!\n"; }

    Now this may not be exactly what are you testing for (i.e. you might want to exclude leading or trailing spaces), but this gives you something to work with. I'll leave the rest up to you and you need help with that, just holler...

Re: Need regex to check for disallowed characters
by blue_cowdawg (Monsignor) on Apr 09, 2004 at 19:36 UTC

        Can anyone please help me with this.

    perldoc perlre

    You could also try posting what you have tried and has failed and let us monks have somewhere to start...

      i've tried /(\W)*(\d)*(\s){2,}/ but because of the \W it ignores the \s{2,}. What i need is something that will allow only one space.

            What i need is something that will allow only one space.

        From perldoc perlre:

                   {n}    Match exactly n times 
                   {n,}   Match at least n times
                   {n,m}  Match at least n but not more than m times
         
        
        If you want to match exactly one space you could either use just \s or \s{1}.

Re: Need regex to check for disallowed characters
by jaco (Pilgrim) on Apr 09, 2004 at 20:28 UTC
    !~ /\s{2,}|[^A-Za-z ]/g

Re: Need regex to check for disallowed characters
by Anomynous Monk (Scribe) on Apr 09, 2004 at 20:07 UTC
    Perhaps it would be easiest to just use more than one RE. Another easy way is to check that it doesn't match what you don't want:
    $input !~ /\d|\pP|\s.*?\s/;
    (Not sure if you mean more than one consecutive space or just more than one space; or if you mean whitespace characters or just the space character; adjust to suit.)

    I see in a followup that you perhaps mean any non-word non-space character when you say punctuation. So maybe something like: /[^\w\s]|\d|\s{2}/ (which will still allow _; if you don't want that, say /[^\w\s]|[\d_]|\s{2}/).